Sha256: e1aa4c9ddea08afd1bea397f777bdcba0a6aa17d1677700758d528f4332f8b32

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

# encoding: utf-8
require 'active_support/inflector'

# AttrEnumerable
module AttrEnumerable
  ATTR_METHODS = [
    { regexp: /^each_(.*)_with_index$/, call_method: :each_attr_with_index },
    { regexp: /^each_(.*)$/, call_method: :each_attr },
    { regexp: /^reverse_(.*)$/, call_method: :reverse_attr },
    { regexp: /^at_(.*)$/, call_method: :at_attr },
    { regexp: /^compact_(.*)$/, call_method: :compact_attr },
    { regexp: /^concat_(.*)$/, call_method: :concat_attr },
    { regexp: /^delete_(.*)$/, call_method: :delete_attr },
    { regexp: /^first_(.*)$/, call_method: :first_attr },
    { regexp: /^include_(.*)\?$/, call_method: :include_attribute? }
  ]

  # call attr enumerable method.
  def method_missing(method_name, *args, &block)
    target_method = detect(method_name)
    send(target_method[:call_method], target_method[:attribute], method_name, *args, &block)
  rescue
   raise
  end

  private
  def detect(method_name)
    ATTR_METHODS.each do |target_method|
      regexp = target_method[:regexp]
      if method_name.to_s =~ regexp
        attribute = method_name.to_s.scan(regexp).first.first
        return { call_method: target_method[:call_method], attribute: attribute }
      end
    end
    fail NoMethodError, "method is not exists #{method_name}"
  end

  def include_attr?(element, attribute)
    element.instance_variables.include? :"@#{attribute}"
  end

  def collection
    instance_variable_get("@#{self.class.name.underscore}")
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tbpgr_utils-0.0.143 lib/attr_enumerable/attr_enumerable_helper.rb