Sha256: 29b0a95e36a8d5bc0133905b5588fdf00f0ee2fee37e3eb1c3883cec5d3e26f6

Contents?: true

Size: 1.67 KB

Versions: 98

Compression:

Stored size: 1.67 KB

Contents

# encoding: utf-8
require 'active_support'

# attr_accessor + initialize
module AttributesInitializable
  extend ActiveSupport::Concern

  module ClassMethods
    # generate attr_accessor + initialize
    # params
    # - symbols : attribute names
    def attr_accessor_init(*symbols)
      generate_attr_accessor(symbols)
      generate_initializer(symbols)
    end

    # generate attr_reader + initialize
    # params
    # - symbols : attribute names
    def attr_reader_init(*symbols)
      generate_attr_reader(symbols)
      generate_initializer(symbols)
    end

    # generate attr_writer + initialize
    # params
    # - symbols : attribute names
    def attr_writer_init(*symbols)
      generate_attr_writer(symbols)
      generate_initializer(symbols)
    end

    private

    def generate_attr_accessor(symbols)
      generate_attr symbols, :accessor
    end

    def generate_attr_reader(symbols)
      generate_attr symbols, :reader
    end

    def generate_attr_writer(symbols)
      generate_attr symbols, :writer
    end

    def generate_attr(symbols, type)
      results = symbols.reduce([]) do |results, sym|
        fail TypeError, "invalid type #{sym.class}. you have to use Symbol" unless sym.class == Symbol
        results << ":#{sym.to_s}"
      end
      class_eval "attr_#{type.to_s} #{results.join(',')}"
    end

    def generate_initializer(symbols)
      instance_eval do
        define_method :initialize do |values = nil, &block|
          return block.call self if block
          symbols.each { |symbol|instance_variable_set("@#{symbol.to_s}", values[symbol]) }
        end
      end
    end
  end
end

Version data entries

98 entries across 98 versions & 1 rubygems

Version Path
tbpgr_utils-0.0.96 lib/attributes_initializable.rb
tbpgr_utils-0.0.95 lib/attributes_initializable.rb
tbpgr_utils-0.0.94 lib/attributes_initializable.rb
tbpgr_utils-0.0.93 lib/attributes_initializable.rb
tbpgr_utils-0.0.92 lib/attributes_initializable.rb
tbpgr_utils-0.0.91 lib/attributes_initializable.rb
tbpgr_utils-0.0.90 lib/attributes_initializable.rb
tbpgr_utils-0.0.89 lib/attributes_initializable.rb
tbpgr_utils-0.0.88 lib/attributes_initializable.rb
tbpgr_utils-0.0.87 lib/attributes_initializable.rb
tbpgr_utils-0.0.86 lib/attributes_initializable.rb
tbpgr_utils-0.0.85 lib/attributes_initializable.rb
tbpgr_utils-0.0.84 lib/attributes_initializable.rb
tbpgr_utils-0.0.83 lib/attributes_initializable.rb
tbpgr_utils-0.0.82 lib/attributes_initializable.rb
tbpgr_utils-0.0.81 lib/attributes_initializable.rb
tbpgr_utils-0.0.80 lib/attributes_initializable.rb
tbpgr_utils-0.0.79 lib/attributes_initializable.rb
tbpgr_utils-0.0.78 lib/attributes_initializable.rb
tbpgr_utils-0.0.77 lib/attributes_initializable.rb