module LocalStore

Provides a class level local data store with namespaces support.

API:

When calling `localstore` at the top of a class definition, class and instance methods are created automatically:

@example Local storage from class and instance methods

require 'localstore'

class TestLocalStore
  extend LocalStore

  # Initialize namespace
  localstore :test
end

# Class methods#
TestLocalStore.test_store :hello, 'world'
p TestLocalStore.test_fetch :hello
p TestLocalStore.test_fetch
TestLocalStore.test_flush
p TestLocalStore.test_fetch

# Instance methods
obj = TestLocalStore.new
obj.test_store :hello2, 'world2'
p obj.test_fetch :hello2
p obj.test_fetch
obj.test_flush
p obj.test_fetch

Constants

NAME

Library name

VERSION

Semantic version number

Attributes

_local_store[R]

@!visibility private

Public Instance Methods

create_class_methods(namespace) click to toggle source

Create class metods according to the namespace

@api private

@param namespace [Symbol, String]

# File lib/localstore.rb, line 80
def create_class_methods(namespace)
  self.class.send :define_method, "#{namespace}_store" do |key, value|
    @_local_store[namespace][key] = value
  end

  self.class.send :define_method, "#{namespace}_fetch" do |key = nil|
    return @_local_store[namespace] if key.nil?

    @_local_store[namespace].fetch key
  end

  self.class.send :define_method, "#{namespace}_flush" do
    @_local_store[namespace] = {}
  end
end
create_instance_methods(namespace) click to toggle source

Create instance methods according to a namespace. They are only proxy methods to class methods

@api private

@param namespace [Symbol, String]

# File lib/localstore.rb, line 102
def create_instance_methods(namespace)
  define_method "#{namespace}_store" do |key, value|
    self.class.send "#{namespace}_store", key, value
  end

  define_method "#{namespace}_fetch" do |key = nil|
    self.class.send "#{namespace}_fetch", key
  end

  define_method "#{namespace}_flush" do
    self.class.send "#{namespace}_flush"
  end
end
localstore(namespace) click to toggle source

Create a new namespace in the local store and create dynamic class methods to interact with the store

@param namespace [Symbol, String] namespace to create

# File lib/localstore.rb, line 57
def localstore(namespace)
  localstores namespace
end
localstores(*namespaces) click to toggle source

Create multiple new namespaces in the local store and create dynamic class methods to interact with the store

@param namespaces [Array<Symbol>, Array<String>] namespaces to create

# File lib/localstore.rb, line 65
def localstores(*namespaces)
  namespaces.each do |namespace|
    @_local_store ||= {}
    @_local_store[namespace] ||= {}

    create_class_methods namespace
    create_instance_methods namespace
  end
end