Sha256: bf551e439a58fb67aa5c3351ac8d946414fd696076ab7772ff9990f743db55c7

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

require 'representable'

module Roar
  module Representer
    def self.included(base)
      base.class_eval do
        include Representable
        extend ClassMethods
      end
    end
    
      
    module ClassMethods
      # Creates a representer instance and fills it with +attributes+.
      # DISCUSS: remove.
      def from_attributes(attributes) # DISCUSS: better move to #new? how do we handle the original #new then?
        new.tap do |representer|
          yield representer if block_given?
          attributes.each { |p,v| representer.public_send("#{p}=", v) }
        end
      end
    end
    
    
    # Convert representer's attributes to a nested attributes hash.
    def to_attributes
      {}.tap do |attributes|
        self.class.representable_attrs.each do |definition|
          value = public_send(definition.getter)
          
          if definition.typed?
            value = definition.apply(value) do |v|
              v.to_attributes  # applied to each typed attribute (even in collections).
            end
          end
          
          attributes[definition.name] = value
        end
      end
    end
  
  private
    def before_serialize(*)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
roar-0.9.0 lib/roar/representer.rb