Module: Serializer::ClassMethods
- Defined in:
- lib/serializer.rb
Instance Method Summary collapse
-
#has_serialized(name, &block) ⇒ Object
Add serializer to a class.
Instance Method Details
#has_serialized(name, &block) ⇒ Object
Add serializer to a class.
Usage:
has_serialized :settings do |settings|
settings.define :tw_share, default: true, type: :boolean
settings.define :fb_share, default: true, type: :boolean
end
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/serializer.rb', line 22 def has_serialized(name, &block) serialize name, Hash initializer = Serializer::Initializer.new block.call(initializer) initializer.each do |method, | define_method "#{method}" do hash = send(name) result = hash[method.to_sym] if hash if hash.nil? or result.nil? send("#{name}=", {}) unless send(name) hash = send(name) result = [:default] result = result.clone if result.duplicable? hash[method.to_sym] = result end return result end define_method "#{method}?" do hash = send(name) result = hash[method.to_sym] if hash if hash.nil? or result.nil? send("#{name}=", {}) unless send(name) hash = send(name) result = [:default] result = result.clone if result.duplicable? hash[method.to_sym] = result end return result end define_method "#{method}=" do |value| original = send(name) || {} if [:type] and value case [:type].to_sym when :float then value = value.to_f if value.respond_to? :to_f when :integer then value = value.to_i if value.respond_to? :to_i when :string then value = value.to_str if value.respond_to? :to_str when :symbol then value = value.to_sym if value.respond_to? :to_sym when :boolean then value = true if value.eql? "true" value = false if value.eql? "false" value = !value.to_i.zero? if value.respond_to? :to_i end end modified = original.clone modified[method.to_sym] = value send("#{name}_will_change!") unless modified.eql?(original) send("#{name}=", modified) end end end |