Module: Serializer::ClassMethods

Defined in:
lib/serializer.rb

Instance Method Summary collapse

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
# 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, options|
    
    define_method "#{method}" do
      hash = send(name)
      result = hash[method.to_sym] if hash
      return options[:default] if hash.nil? or result.nil?
      return result
    end
    
    define_method "#{method}?" do
      hash = send(name)
      result = hash[method.to_sym] if hash
      return options[:default] if hash.nil? or result.nil?
      return result
    end
    
    define_method "#{method}=" do |value|
      send("#{name}=", {}) unless send(name)
      hash = send(name)
      
      if options[:type] and value
        case options[: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
      
      send(name)[method.to_sym] = value
    end
    
  end
end