Sha256: d37ae9370d7c288332d5d845f07fd896c8d83670bf618ed06d7852b6d0383621

Contents?: true

Size: 1.77 KB

Versions: 3

Compression:

Stored size: 1.77 KB

Contents

require 'active_support/concern'

module ActiveHouse
  module Modeling
    extend ActiveSupport::Concern

    included do
      class_attribute :_attribute_opts, instance_writer: false
      self._attribute_opts = {}

      private

      def parse_attribute_method_name(method_name)
        name, is_setter = method_name.to_s.match(/\A(.+)?(=)?\z/).captures
        name = name.to_sym
        is_setter = !is_setter.nil?
        [name, is_setter]
      end

      def attribute_method?(name, is_setter, *args)
        (_attribute_opts.key?(name) || @_attributes.key?(name)) && (is_setter ? args.size.one? : true)
      end

      def get_attribute(name)
        @_attributes[name]
      end

      def set_attribute(name, value)
        @_attributes[name] = value
      end
    end

    class_methods do
      def attribute(name, options = {})
        name = name.to_sym
        self._attribute_opts = _attribute_opts.merge(name => options)
      end

      def attributes(*names)
        options = names.extract_options!
        names.each { |name| attributes(name, options.dup) }
      end
    end

    def initialize(params = {})
      @_attributes = {}
      assign_attributes(params)
    end

    def as_json(*_args)
      to_h
    end

    def to_h
      @_attributes.dup
    end

    def [](key)
      @_attributes[key.to_sym]
    end

    def respond_to_missing?(method_name, *args)
      name, is_setter = parse_attribute_method_name(method_name)
      attribute_method?(name, is_setter, *args)
    end

    def method_missing(method_name, *args, &block)
      name, is_setter = parse_attribute_method_name(method_name)
      if attribute_method?(name, is_setter, *args)
        is_setter ? set_attribute(name, args.first) : get_attribute(name)
      else
        super
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
active_house-0.1.2 lib/active_house/modeling.rb
active_house-0.1.1 lib/active_house/modeling.rb
active_house-0.1.0 lib/active_house/modeling.rb