Skip to content
This repository has been archived by the owner on Oct 19, 2018. It is now read-only.

how to make public_state work for class and singleton class

Mitch VanDuyn edited this page Feb 7, 2017 · 2 revisions
module HyperStore
  module ClassMethods 
    def state_reader(*args)
      name, opts = [args.first.is_a?(Hash) ? nil : args.shift,  args[0] || {}]
      opts = {name => nil}.merge(opts) if name
      opts[:scope] ||= :instance
      puts "defining public_state(#{opts})"
    end
    def private_state(*args)
      name, opts = [args.first.is_a?(Hash) ? nil : args.shift,  args[0] || {}]
      opts[:as] = nil
      state_reader(name, opts)
    end
  end
  class Base  
    def self.inherited(child)
      child.extend(ClassMethods)
      [:state_reader, :private_state].each do |method|
        child.singleton_class.define_singleton_method(method) do |*args|
          name, opts = [args.first.is_a?(Hash) ? nil : args.shift,  args[0] || {}]
          opts[:scope] ||= :class
          child.send(method, name, opts)
        end
      end
    end
  end
end

class Store < HyperStore::Base
  state_reader :foo_is_instance
  state_reader :foo_is_class, scope: :class
  state_reader foo_is_initialized: 12
  class << self 
    state_reader :bar_is_instance, scope: :instance
    state_reader :bar_is_class
    state_reader bar_is_initialized: 12
  end
end
Clone this wiki locally