Class: PPT::Presenters::Entity

Inherits:
Object
  • Object
show all
Defined in:
lib/simple-orm/presenters.rb

Direct Known Subclasses

Developer, Story, User

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values = Hash.new) ⇒ Entity

Returns a new instance of Entity.



113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/simple-orm/presenters.rb', line 113

def initialize(values = Hash.new)
  # Let's consider it safe since this is not user input.
  # It might not be the best idea, but for now, who cares.
  values = PPT.symbolise_keys(values)

  values.each do |key, value|
    unless attribute = self.attributes[key]
      raise ArgumentError.new("No such attribute: #{key}")
    end

    attribute.set(value)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



133
134
135
136
137
138
139
140
141
# File 'lib/simple-orm/presenters.rb', line 133

def method_missing(name, *args, &block)
  if self.attributes.has_key?(name)
    self.attributes[name].get
  elsif name[-1] == '=' && self.attributes.has_key?(name.to_s[0..-2].to_sym)
    self.attributes[name.to_s[0..-2].to_sym].set(args.first)
  else
    super(name, *args, &block)
  end
end

Class Method Details

.attribute(name, options = Hash.new) ⇒ Object



109
110
111
# File 'lib/simple-orm/presenters.rb', line 109

def self.attribute(name, options = Hash.new)
  self.attributes[name] = Attribute.new(name)
end

.attributesObject



105
106
107
# File 'lib/simple-orm/presenters.rb', line 105

def self.attributes
  @attributes ||= Hash.new
end

Instance Method Details

#attributesObject



127
128
129
130
131
# File 'lib/simple-orm/presenters.rb', line 127

def attributes
  @attributes ||= self.class.attributes.reduce(Hash.new) do |buffer, (name, attribute)|
    buffer.merge(name => attribute.dup.tap { |attribute| attribute.instance = self })
  end
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


143
144
145
146
147
# File 'lib/simple-orm/presenters.rb', line 143

def respond_to_missing?(name, include_private = false)
  self.attributes.has_key?(name) ||
    name[-1] == '=' && self.attributes.has_key?(name.to_s[0..-2].to_sym) ||
    super(name, include_private)
end

#to_jsonObject



157
158
159
# File 'lib/simple-orm/presenters.rb', line 157

def to_json
  self.values.to_json
end

#validateObject



161
162
163
164
165
# File 'lib/simple-orm/presenters.rb', line 161

def validate
  self.attributes.each do |_, attribute|
    attribute.validate!
  end
end

#values(stage = nil) ⇒ Object



149
150
151
152
153
154
155
# File 'lib/simple-orm/presenters.rb', line 149

def values(stage = nil)
  self.attributes.reduce(Hash.new) do |buffer, (name, attribute)|
    value = attribute.get(stage)
    buffer[name] = value if value && value != ''
    buffer
  end
end