Class: Modular::Helpers::AbstractModel

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming
Includes:
ActiveModel::Conversion, ActiveModel::Validations
Defined in:
lib/modular/helpers.rb

Direct Known Subclasses

Components::Base

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ AbstractModel

Returns a new instance of AbstractModel.



10
11
12
13
14
15
16
# File 'lib/modular/helpers.rb', line 10

def initialize(attributes = {})
  @attributes ||= ActiveSupport::HashWithIndifferentAccess.new
  
  attributes.each do |name, value|
    @attributes[name.to_s] = value
  end
end

Class Method Details

.attr_accessor(*fields) ⇒ Object



46
47
48
49
50
51
# File 'lib/modular/helpers.rb', line 46

def self.attr_accessor(*fields)
  fields.each do |field|
    attr_writer field
    attr_reader field
  end
end

.attr_accessor_with_default(sym, default = Proc.new) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/modular/helpers.rb', line 53

def self.attr_accessor_with_default(sym, default = Proc.new)
  define_method(sym, block_given? ? default : Proc.new { default })
  module_eval(<<-EVAL, __FILE__, __LINE__ + 1)
    def #{sym}=(value)                          # def age=(value)
      class << self; attr_accessor :#{sym} end  #   class << self; attr_accessor :age end
      @attributes['#{sym}']=value               #   @attributes['age'] = value
    end                                         # end
  EVAL
end

.attr_reader(*fields) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/modular/helpers.rb', line 26

def self.attr_reader(*fields)
  fields.each do |field|
    class_eval <<EOF
  def #{field}
    @attributes['#{field}']
  end
EOF
  end
end

.attr_reader_with_default(sym, default = Proc.new) ⇒ Object



63
64
65
66
67
68
69
70
71
# File 'lib/modular/helpers.rb', line 63

def self.attr_reader_with_default(sym, default = Proc.new)
  define_method(sym, block_given? ? default : Proc.new { default })
  module_eval(<<-EVAL, __FILE__, __LINE__ + 1)
    def #{sym}=(value)                          # def age=(value)
      class << self; attr_reader :#{sym} end    #   class << self; attr_accessor :age end
      @attributes['#{sym}']=value               #   @attributes['age'] = value
    end                                         # end
  EVAL
end

.attr_writer(*fields) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/modular/helpers.rb', line 36

def self.attr_writer(*fields)
  fields.each do |field|
    class_eval <<EOF
  def #{field}=(value)
    @attributes['#{field}']=value
  end
EOF
  end
end

Instance Method Details

#persisted?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/modular/helpers.rb', line 18

def persisted?
  false
end

#to_jsonObject



22
23
24
# File 'lib/modular/helpers.rb', line 22

def to_json
  ActiveSupport::JSON.encode @attributes.merge({:type => type})
end