Module: BBFlow::Persistent

Included in:
Github, Trello, Updater
Defined in:
lib/bb_flow/persistent.rb

Overview

A bit of meta programming that allows to replace

def trello_key
  @trello_key ||= Config.global.transaction do |store|
    store['trello'] ||= {}
    store['trello']['key'] ||= Printer.ask('Go to https://trello.com/app-key and paste Key: ')
  end
end

with

class Trello
  extend Persistent

  persistent global def key
    Printer.ask('Go to https://trello.com/app-key and paste Key: ')
  end
end

The method with be memoized both within and across executions.

Defined Under Namespace

Classes: Store

Instance Method Summary collapse

Instance Method Details

#global(method_name) ⇒ Object



53
54
55
56
57
# File 'lib/bb_flow/persistent.rb', line 53

%i(global local).each do |store_helper|
  define_method(store_helper) do |method_name|
    [Store.get(store_helper), method_name]
  end
end

#local(method_name) ⇒ Array<Config, Symbol>

Note:

intended to be used with #persistent

Parameters:

  • method_name (Symbol)

Returns:

  • (Array<Config, Symbol>)


53
54
55
56
57
# File 'lib/bb_flow/persistent.rb', line 53

%i(global local).each do |store_helper|
  define_method(store_helper) do |method_name|
    [Store.get(store_helper), method_name]
  end
end

#persistent(args) ⇒ Object

Parameters:

  • args (Array<Config, Symbol>)


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/bb_flow/persistent.rb', line 26

def persistent(args)
  store, method_name = args

  module_with_persistent_method = Module.new do
    define_method(method_name) do
      prefix = name.gsub(/^.*::/, '').downcase
      instance_variable_name = "@#{method_name}_memo"

      accessor = proc do |hash|
        hash[prefix] ||= {}
        hash[prefix][method_name.to_s] ||= super()
      end

      instance_variable_get(instance_variable_name) ||
      instance_variable_set(instance_variable_name, (store.instance_variable_get('@lock').locked? ? accessor.call(store) : store.transaction(&accessor)))
    end
  end

  prepend module_with_persistent_method
end