Sha256: 2ef39758c4d93d897850abc09f5222f2f8aabb5517b7b0db61749748d7c33078

Contents?: true

Size: 1.12 KB

Versions: 3

Compression:

Stored size: 1.12 KB

Contents

# frozen_string_literal: true

module LazyRecord
  # Macro for dynamic instance method generation. Best to use for one-liners.
  module Methods
    METHODS_MODULE_NAME = :DynamicMethods

    # Defines an instance method on the calling class. The first agrument
    # is a symbol that names the method. The second argument should be a lambda
    # that defines the method execution. The method argument could technically
    # be any object that responds to #to_proc and returns a Proc, but lambdas
    # with their arity restrictions are preferred.
    #
    # === Example
    #   class Thing < LazyRecord::Base
    #     lr_method :say_hi, -> { "Hi from #{self}" }
    #   end
    #
    #   thing = Thing.new # => #<Thing>
    #   thing.say_hi      # => "Hi from #<Thing:0x007fb9629c6260>"
    #
    # @api public
    #
    # @param method_name [Symbol, String]
    # @param method [Proc]
    #
    # @return [Symbol]
    def lr_method(method_name, method)
      mod = get_or_set_mod(METHODS_MODULE_NAME)

      mod.module_eval do
        define_method(method_name.to_sym, &method)
      end

      include mod unless include?(mod)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lazy_record-0.7.2 lib/lazy_record/methods.rb
lazy_record-0.7.1 lib/lazy_record/methods.rb
lazy_record-0.7.0 lib/lazy_record/methods.rb