mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
Add accessors to settings class
This commit is contained in:
parent
c65d387705
commit
41f1855056
@ -1,16 +1,18 @@
|
|||||||
|
require 'active_support/hash_with_indifferent_access'
|
||||||
|
|
||||||
module ActiveModel
|
module ActiveModel
|
||||||
class Serializer
|
class Serializer
|
||||||
class Settings
|
class Settings
|
||||||
def initialize
|
def initialize
|
||||||
@data = {}
|
@data = ActiveSupport::HashWithIndifferentAccess.new
|
||||||
end
|
end
|
||||||
|
|
||||||
def [](key)
|
def [](key)
|
||||||
@data[key.to_s]
|
@data[key]
|
||||||
end
|
end
|
||||||
|
|
||||||
def []=(key, value)
|
def []=(key, value)
|
||||||
@data[key.to_s] = value
|
@data[key] = value
|
||||||
end
|
end
|
||||||
|
|
||||||
def each(&block)
|
def each(&block)
|
||||||
@ -20,6 +22,17 @@ module ActiveModel
|
|||||||
def clear
|
def clear
|
||||||
@data.clear
|
@data.clear
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def method_missing(name, *args)
|
||||||
|
return @data[name] if @data.include?(name)
|
||||||
|
match = name.to_s.match(/(.*?)([?=]?)$/)
|
||||||
|
case match[2]
|
||||||
|
when "="
|
||||||
|
@data[match[1]] = args.first
|
||||||
|
when "?"
|
||||||
|
!!@data[match[1]]
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
SETTINGS = Settings.new
|
SETTINGS = Settings.new
|
||||||
|
|||||||
@ -43,6 +43,25 @@ module ActiveModel
|
|||||||
ensure
|
ensure
|
||||||
SETTINGS.clear
|
SETTINGS.clear
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_setup_config_accessors
|
||||||
|
ActiveModel::Serializer.setup do |config|
|
||||||
|
config.foo = 'v1'
|
||||||
|
config.bar = 'v2'
|
||||||
|
end
|
||||||
|
|
||||||
|
assert_equal 'v1', SETTINGS.foo
|
||||||
|
assert_equal 'v2', SETTINGS.bar
|
||||||
|
ensure
|
||||||
|
SETTINGS.clear
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_setup_acessor_when_nil
|
||||||
|
assert_nil SETTINGS.foo
|
||||||
|
SETTINGS.foo = 1
|
||||||
|
assert 1, SETTINGS.foo
|
||||||
|
assert_nil SETTINGS.bar
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user