lib/sinclair.rb in sinclair-1.1.3 vs lib/sinclair.rb in sinclair-1.2.0
- old
+ new
@@ -6,11 +6,11 @@
# @api public
# @author darthjee
#
# Builder that add instance methods to a class
#
-# @example
+# @example Stand alone usage
# class MyModel
# end
#
# buider = Sinclair.new(MyModel)
#
@@ -36,32 +36,62 @@
#
# @param klass [Class] to receive the methods
# @param options [Hash] open hash options to be used by builders inheriting from Sinclair
# through the Sinclair::OptionsParser concern
#
- # @example
+ # @example Preparing builder
#
# class Purchase
# def initialize(value, quantity)
# @value = value
# @quantity = quantity
# end
# end
#
# builder = Sinclair.new(Purchase)
#
- # @example
+ # @example Passing building options (Used on subclasses)
#
- # builder = Sinclair.new(Purchase, rescue_error: true)
+ # class MyBuilder < Sinclair
+ # def add_methods
+ # if options_object.rescue_error
+ # add_safe_method
+ # else
+ # add_method(:symbolize) { @variable.to_sym }
+ # end
+ # end
+ #
+ # def add_safe_method
+ # add_method(:symbolize) do
+ # begin
+ # @variable.to_sym
+ # rescue StandardError
+ # :default
+ # end
+ # end
+ # end
+ # end
+ #
+ # class MyModel
+ # end
+ #
+ # builder = MyBuilder.new(MyModel, rescue_error: true)
+ #
+ # builder.add_method
+ # builder.build
+ #
+ # instance = MyModel.new
+ #
+ # instance.symbolize # returns :default
def initialize(klass, options = {})
@klass = klass
@options = options
end
# builds all the methods added into the klass
#
- # @example
+ # @example Adding a default value method
#
# class MyModel
# end
#
# buider = Sinclair.new(MyModel)
@@ -112,17 +142,17 @@
# builder.add_method(:bond_name) { "#{last_name}, #{full_name}" }
# builder.build
#
# Person.new('john', 'wick').bond_name # returns 'wick, john wick'
# @return [Array<MethodDefinition>]
- def add_method(name, code = nil, &block)
- definitions << MethodDefinition.new(name, code, &block)
+ def add_method(name, code = nil, **options, &block)
+ definitions << MethodDefinition.new(name, code, **options, &block)
end
# Evaluetes a block which will result in a String, the method code
#
- # @example
+ # @example Building a initial value class method
#
# module InitialValuer
# extend ActiveSupport::Concern
#
# class_methods do
@@ -145,11 +175,11 @@
# object = MyClass.new
# object.age # 20
# object.age = 30
# object.age # 30
#
- # @example
+ # @example Adding option for rescue
#
# class Purchase
# def initialize(value, quantity)
# @value = value
# @quantity = quantity
@@ -166,10 +196,10 @@
#
# builder.build
#
# Purchase.new(2.3, 5).total_price # raises error
#
- # @example
+ # @example Using option for rescue
#
# builder = Sinclair.new(Purchase, rescue_error: true)
#
# builder.eval_and_add_method(:total_price) do
# code = 'self.value * self.quantity'