Sha256: 123b9a0caf2c0f0ef4cade2143c0d75a8096451a0c97d07a711dbc02b74dfa60

Contents?: true

Size: 1.63 KB

Versions: 2

Compression:

Stored size: 1.63 KB

Contents

module Restly::Base::Fields
  extend ActiveSupport::Concern

  included do
    extend  ClassMethods

    class_attribute :fields
    self.fields = FieldSet.new(self)
    field :id

    inherited do
      self.fields = fields.dup
    end

  end

  module ClassMethods

    private

    def field(attr)
      if attr.is_a?(Symbol) || attr.is_a?(String)
        define_attribute_method attr unless instance_method_already_implemented? attr
        self.fields += [attr]
      else
        raise Restly::Error::InvalidField, "field must be a symbol or string."
      end
    end

    def exclude_field(name)
      self.fields -= [name]
    end

  end

  class FieldSet < Set

    attr_reader :owner

    def initialize(owner, fields=[])
      @owner = owner
      super(fields)

      self.each { |value| owner.send(:define_attribute_method, value) unless owner.send(:instance_method_already_implemented?, value.to_sym) }
    end

    def include?(value)
      super(value.to_sym) || super(value.to_s)
    end

    def <<(value)
      owner.send(:define_attribute_method, value) unless owner.send(:instance_method_already_implemented?, value.to_sym)
      super(value.to_sym)
    end

    def +(other_array)
      other_array.map!(&:to_sym)
      other_array.each { |value| owner.send(:define_attribute_method, value) unless owner.send(:instance_method_already_implemented?, value.to_sym) }
      super(other_array)
    end

    def -(other_array)
      other_array.map!(&:to_sym)
      other_array.each { |value| owner.send(:define_attribute_method, value) if owner.send(:instance_method_already_implemented?, value.to_sym) }
      super(other_array)
    end

  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
restly-0.0.1.alpha.19 lib/restly/base/fields.rb
restly-0.0.1.alpha.18 lib/restly/base/fields.rb