Class: Adapt::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/adapt/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



53
54
55
# File 'lib/adapt/base.rb', line 53

def initialize(attributes={})
  self.attributes = attributes
end

Class Method Details

.property(name, options = {}, &block) ⇒ Object



10
11
12
13
14
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
45
46
47
48
49
50
51
# File 'lib/adapt/base.rb', line 10

def self.property(name, options={}, &block)
  unless default = options.delete(:default)
    attr_reader(name)
  else
    define_method(name) do
      unless instance_variable_defined?(:"@#{name}")
        send(:"#{name}=", default)
      end

      instance_variable_get(:"@#{name}")
    end
  end

  type = if block_given?
    const_set(
      name.to_s.classify,
      Class.new(Base).tap { |base| base.class_eval(&block) }
    )
  else
    options.delete(:type)
  end

  unless type
    attr_writer(name)
  else
    collection = options.delete(:collection) || type.is_a?(Array)
    type = type.first if type.is_a?(Array)

    define_method(:"#{name}=") do |value|
      value = unless collection
        type.new(value)
      else
        value.collect { |attributes| attributes.is_a?(Hash) ? type.new(attributes) : attributes }
      end

      instance_variable_set(:"@#{name}", value)
    end
  end

  validates(name, options) if options.any?
  properties << name unless properties.include?(name)
end

Instance Method Details

#attributesObject



57
58
59
60
61
62
63
64
# File 'lib/adapt/base.rb', line 57

def attributes
  attributes = properties.each_with_object({}) do |name, attributes|
    value = send(name)
    attributes[name] = value unless value.nil?
  end

  encode_keys(attributes)
end

#attributes=(attributes) ⇒ Object



66
67
68
69
70
# File 'lib/adapt/base.rb', line 66

def attributes=(attributes)
  attributes.each do |key, value|
    send(:"#{decode_key(key)}=", value)
  end
end

#from_json(json) ⇒ Object



76
77
78
79
# File 'lib/adapt/base.rb', line 76

def from_json(json)
  self.attributes = ActiveSupport::JSON.decode(json)
  self
end

#to_jsonObject



72
73
74
# File 'lib/adapt/base.rb', line 72

def to_json
  ActiveSupport::JSON.encode(attributes)
end