Module: GiftWrap::Presenter
- Defined in:
- lib/gift_wrap/presenter.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#attributes ⇒ Object
For use by ActiveModel::Serializers::JSON in building a default set of values when calling #as_json or #to_json.
-
#initialize(wrapped_object, **options) ⇒ Object
Current options: - associations: a hash mapping association names to the presenter class to use when wrapping the association.
-
#wrapped_association_presenter(association_name) ⇒ Object
Used in methods defined by ::wrap_association to determine the presenter class that is used for a particular association name.
Class Method Details
.included(base) ⇒ Object
4 5 6 7 8 9 |
# File 'lib/gift_wrap/presenter.rb', line 4 def self.included(base) base.extend(ClassMethods) if GiftWrap.config.use_serializers? && defined? ActiveModel::Serializers::JSON base.send(:include, ActiveModel::Serializers::JSON) end end |
Instance Method Details
#attributes ⇒ Object
For use by ActiveModel::Serializers::JSON in building a default set of values when calling #as_json or #to_json
43 44 45 46 47 |
# File 'lib/gift_wrap/presenter.rb', line 43 def attributes self.class.attributes.each.with_object({}) do |msg, attr_hash| attr_hash[msg.to_s] = self.send(msg) end end |
#initialize(wrapped_object, **options) ⇒ Object
Current options:
-
associations: a hash mapping association names to the presenter class to use when wrapping the association. Used to override the :with setting of a call to ::wrap_association at an instance level.
16 17 18 19 |
# File 'lib/gift_wrap/presenter.rb', line 16 def initialize(wrapped_object, **) @wrapped_object = wrapped_object @wrapped_association_presenters = .fetch(:associations, {}) end |
#wrapped_association_presenter(association_name) ⇒ Object
Used in methods defined by ::wrap_association to determine the presenter class that is used for a particular association name. First checks any instance-specific options for the association name, and falls back to those defined by the :with option passed to any ::wrap_association call for said association_name.
26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/gift_wrap/presenter.rb', line 26 def wrapped_association_presenter(association_name) if @wrapped_association_presenters.none? self.class.wrapped_association_defaults.fetch(association_name) do |name| raise NoMethodError.new("No association registered as '#{name}'.") end else @wrapped_association_presenters.fetch( association_name, self.class.wrapped_association_defaults.fetch(association_name) do |name| raise NoMethodError.new("No association registered as '#{name}'.") end) end end |