Class: Webmate::Presenters::Base
- Inherits:
-
Object
- Object
- Webmate::Presenters::Base
- Defined in:
- lib/webmate/presenters/base.rb
Instance Attribute Summary collapse
-
#attrs ⇒ Object
readonly
Returns the value of attribute attrs.
Instance Method Summary collapse
- #attribute(attr, &block) ⇒ Object
- #attributes(*attrs, &block) ⇒ Object
-
#initialize(object, options = {}) ⇒ Base
constructor
A new instance of Base.
- #namespace(name, &block) ⇒ Object
- #resource(name, object = nil, &block) ⇒ Object
- #resources(name, objects = nil, &block) ⇒ Object
Constructor Details
#initialize(object, options = {}) ⇒ Base
Returns a new instance of Base.
5 6 7 8 |
# File 'lib/webmate/presenters/base.rb', line 5 def initialize(object, = {}) @object, @options = object, .with_indifferent_access @attrs = {} end |
Instance Attribute Details
#attrs ⇒ Object (readonly)
Returns the value of attribute attrs.
3 4 5 |
# File 'lib/webmate/presenters/base.rb', line 3 def attrs @attrs end |
Instance Method Details
#attribute(attr, &block) ⇒ Object
55 56 57 |
# File 'lib/webmate/presenters/base.rb', line 55 def attribute(attr, &block) self.attrs[attr.to_s] = yield end |
#attributes(*attrs, &block) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/webmate/presenters/base.rb', line 42 def attributes(*attrs, &block) if @object.blank? object = attrs.last attrs.delete(attrs.last) raise ArgumentError, "Object was not specified" if object.is_a?(Symbol) end target = object || @object Array.wrap(attrs).flatten.each do |attribute| self.attrs[attribute.to_s] = target.send(attribute.to_s) end end |
#namespace(name, &block) ⇒ Object
10 11 12 13 14 |
# File 'lib/webmate/presenters/base.rb', line 10 def namespace(name, &block) serializer = self.class.new(@object, @options) serializer.instance_exec(@object, &block) self.attrs[name] = serializer.attrs end |
#resource(name, object = nil, &block) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/webmate/presenters/base.rb', line 16 def resource(name, object = nil, &block) raise "You should set name for resource" if name.blank? raise "You should specify object" if @object.nil? && object.nil? nested_name = name.to_s nested_object = object || @object.send(nested_name) if nested_object.blank? self.attrs[nested_name] = {} else self.attrs[nested_name] = nested_resource(nested_name, nested_object, @options, &block) end end |
#resources(name, objects = nil, &block) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/webmate/presenters/base.rb', line 28 def resources(name, objects = nil, &block) raise "You should specify object" if @object.nil? && objects.nil? objects = objects.flatten unless objects.nil? nested_objects = objects || @object.send(name.to_s) if nested_objects.blank? self.attrs[name.to_s] = [] else self.attrs[name.to_s] = (nested_objects || []).inject([]) do |result, obj| resource = nested_resource(name, obj, @options, &block) resource.empty? ? result : (result << resource) end end end |