Module: ModelAttribute

Defined in:
lib/model_attribute.rb,
lib/model_attribute/json.rb,
lib/model_attribute/errors.rb,
lib/model_attribute/version.rb

Defined Under Namespace

Modules: InstanceMethods, Json Classes: InvalidAttributeNameError, UnsupportedTypeError

Constant Summary collapse

SUPPORTED_TYPES =
[:integer, :boolean, :string, :time, :json]
VERSION =
"2.0.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



9
10
11
12
13
# File 'lib/model_attribute.rb', line 9

def self.extended(base)
  base.send(:include, InstanceMethods)
  base.instance_variable_set('@attribute_names', [])
  base.instance_variable_set('@attribute_types', {})
end

Instance Method Details

#attribute(name, type) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/model_attribute.rb', line 15

def attribute(name, type)
  name = name.to_sym
  type = type.to_sym
  raise UnsupportedTypeError.new(type) unless SUPPORTED_TYPES.include?(type)

  @attribute_names << name
  @attribute_types[name] = type

  self.class_eval(<<-CODE, __FILE__, __LINE__ + 1)
    def #{name}=(value)
      write_attribute(#{name.inspect}, value, #{type.inspect})
    end

    def #{name}
      read_attribute(#{name.inspect})
    end

    def #{name}_changed?
      !!changes[#{name.inspect}]
    end
  CODE

  if type == :boolean
    self.class_eval(<<-CODE, __FILE__, __LINE__ + 1)
      def #{name}?
        !!read_attribute(#{name.inspect})
      end
    CODE
  end
end

#attributesObject



46
47
48
# File 'lib/model_attribute.rb', line 46

def attributes
  @attribute_names
end