Sha256: 027138f827a67470528dfed94be3c9843317d5621a51af29bd27bf752364ad18

Contents?: true

Size: 1.68 KB

Versions: 2

Compression:

Stored size: 1.68 KB

Contents

class Restfulie::Common::Builder::Base
  attr_accessor :rules_blocks
  attr_accessor :object
  
  # TODO: Configurable
  OPTIONS_DEFAULT = {
    :eagerload => true,
    :default_rule => true
  }

  def initialize(object, rules_blocks = [], options = {})
    @options = OPTIONS_DEFAULT.merge(options)
    @object  = object
    @rules_blocks = rules_blocks
  end

  # Remove to_json from ActiveSupport in the class
  # I want my own to_json
  undef_method :to_json if respond_to?(:to_json)

  def respond_to?(symbol, include_private = false)
    !marshalling_class(symbol).nil? || super
  end

  def method_missing(symbol, *args)
    unless (marshalling = marshalling_class(symbol)).nil?
      return builder(marshalling, *args)
    end
    super
  end

private

  def builder(marshalling, options = {})
    @object.class.ancestors.include?(Enumerable) ? builder_collection(marshalling, options) : builder_member(marshalling, options)
  end

  def builder_member(marshalling, options = {})
    marshalling.new(@object, rules_blocks).builder_member(@options.merge(options))
  end

  def builder_collection(marshalling, options = {})
    marshalling.new(@object, rules_blocks).builder_collection(@options.merge(options))
  end

  def marshalling_class(method)
    if marshalling_name = method.to_s.match(/to_(.*)/)
      marshalling = marshalling_name[1].downcase.capitalize.to_sym
      if Restfulie::Common::Builder::Marshalling.const_defined?(marshalling)
        begin
          Restfulie::Common::Builder::Marshalling.const_get(marshalling) 
        rescue NameError
          raise Restfulie::Common::Error::UndefinedMarshallingError.new("Marshalling #{marshalling} not found.")
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
restfulie-0.7.1 lib/restfulie/common/builder/builder_base.rb
restfulie-0.7.0 lib/restfulie/common/builder/builder_base.rb