class Tardvig::Toolkit

Container which initializes and gives you access to its tools (objects). Useful when you need to do a DSL

Public Class Methods

new(params = {}) click to toggle source

Creates a new toolbox instance and initializes its tools. @param params [Hash] you can set some options (see below) via this hash.

It also will be available as the second argument passed to
the `call` methods of your tools.

@option params [boolean] :initialize_tools (true) initialize tools or not?

If not, you will not able to use them, but you can initialize them
later (see {#create_tools}).
# File lib/tardvig/toolkit.rb, line 31
def initialize(params = {})
  default_params = { initialize_tools: true }
  @params = default_params.merge params
  create_tools if @params[:initialize_tools]
end
tool(name, tool_itself = nil) click to toggle source

Adds a new tool (object).

If the given object has either `call` or `new` methods then result of the method execution will be used as a tool instead. When the `call` method of your tool is executed, the toolkit will be given as the first argument and the `params` (see {#initialize}) as the second. @param name [Symbol] you can access your tool via this method name @param tool_itself [#call, new, Object] your tool.

# File lib/tardvig/toolkit.rb, line 19
def tool(name, tool_itself = nil)
  tools[name] = tool_itself || Proc.new
end
tools() click to toggle source

@return [Hash] your tools

# File lib/tardvig/toolkit.rb, line 7
def tools
  @tools ||= {}
end

Public Instance Methods

create_tools() click to toggle source

You can create tools to use them through this method if you have not done this on toolkit initialize.

# File lib/tardvig/toolkit.rb, line 39
def create_tools
  create_tools_readers
end

Private Instance Methods

create_tools_readers() click to toggle source
# File lib/tardvig/toolkit.rb, line 55
def create_tools_readers
  self.class.tools.each do |name, tool|
    instance_variable_set "@#{name}", tool_initialize(tool)
    define_singleton_method name do
      instance_variable_get "@#{name}"
    end
  end
end
tool_initialize(tool) click to toggle source
# File lib/tardvig/toolkit.rb, line 45
def tool_initialize(tool)
  if tool.respond_to? :call
    tool.call self, @params
  elsif tool.respond_to? :new
    tool.new
  else
    tool
  end
end