Module: Enjoy::HashField::ClassMethods

Defined in:
app/models/concerns/enjoy/hash_field.rb

Instance Method Summary collapse

Instance Method Details

#enjoy_cms_hash_field(name, opts = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'app/models/concerns/enjoy/hash_field.rb', line 6

def enjoy_cms_hash_field(name, opts = {})
  field "#{name}_hash", opts

  class_eval <<-EVAL
    def #{name}_str=(val)
      begin
        self.#{name}_hash = JSON.parse(val)
      rescue
        self[:#{name}_str] = val
      end
    end
    def #{name}_str
      self[:#{name}_str] ||= self.#{name}.to_json
    end
    def #{name}
      self.#{name}_hash
    end

    validate do
      if self.#{name}_str != self.#{name}.to_json
        self.errors.add(:#{name}, "Неверный формат данных")
      else
        self.remove_attribute :#{name}_str
      end
      true
    end
  EVAL
end