lib/characterizable.rb in characterizable-0.0.9 vs lib/characterizable.rb in characterizable-0.0.10
- old
+ new
@@ -1,10 +1,11 @@
require 'set'
require 'blockenspiel'
require 'active_support'
require 'active_support/version'
%w{
+ active_support/core_ext/hash/slice
active_support/core_ext/class/attribute_accessors
active_support/core_ext/object/blank
active_support/core_ext/array/wrap
active_support/core_ext/module/aliasing
active_support/core_ext/module/delegation
@@ -24,49 +25,49 @@
def expire_snapshot!
@_characteristics = nil
end
- # hashes that survive as such when you select/reject/slice them
- # they also keep arguments passed to them
- class SurvivorHash < Hash
- attr_reader :survivor_args
- def initialize(*survivor_args)
- @survivor_args = survivor_args
- end
- def reject(&block)
- inject(self.class.new(*survivor_args)) do |memo, ary|
- unless block.call(*ary)
- memo[ary[0]] = ary[1]
+ class BetterHash < ::Hash
+ # In Ruby 1.9, running select/reject/etc. gives you back a hash
+ if RUBY_VERSION < '1.9'
+ def reject(&block)
+ inject(Characterizable::BetterHash.new) do |memo, ary|
+ unless block.call(*ary)
+ memo[ary[0]] = ary[1]
+ end
+ memo
end
- memo
end
- end
- def select(&block)
- inject(self.class.new(*survivor_args)) do |memo, ary|
- if block.call(*ary)
- memo[ary[0]] = ary[1]
+ def select(&block)
+ inject(Characterizable::BetterHash.new) do |memo, ary|
+ if block.call(*ary)
+ memo[ary[0]] = ary[1]
+ end
+ memo
end
- memo
end
- end
- def slice(*keep)
- inject(self.class.new(*survivor_args)) do |memo, ary|
- if keep.include?(ary[0])
- memo[ary[0]] = ary[1]
+ # I need this because otherwise it will try to do self.class.new on subclasses
+ # which would get "0 for 1" arguments error with Snapshot, among other things
+ def slice(*keep)
+ inject(Characterizable::BetterHash.new) do |memo, ary|
+ if keep.include?(ary[0])
+ memo[ary[0]] = ary[1]
+ end
+ memo
end
- memo
end
end
end
- class Snapshot < SurvivorHash
- def initialize(*survivor_args)
- super
- take_snapshot
+ class Snapshot < BetterHash
+ attr_reader :target
+ def initialize(target)
+ @target = target
+ _take_snapshot
end
- def take_snapshot
+ def _take_snapshot
target.characterizable_base.characteristics.each do |_, c|
if c.known?(target)
if c.effective?(target)
self[c.name] = c.value(target)
elsif !c.untrumped?(target)
@@ -76,20 +77,10 @@
lacking_keys.push c.prerequisite
end
end
end
end
- def slice(*keep)
- copy = self.class.new *survivor_args
- copy.keys.each do |key|
- copy.delete key unless keep.include? key
- end
- copy
- end
- def target
- survivor_args.first
- end
def []=(key, value)
target.expire_snapshot!
super
end
def wasted_keys
@@ -130,10 +121,10 @@
attr_reader :klass
def initialize(klass)
@klass = klass
end
def characteristics
- @_characteristics ||= SurvivorHash.new
+ @_characteristics ||= BetterHash.new
end
include Blockenspiel::DSL
def has(name, options = {}, &block)
characteristics[name] = Characteristic.new(self, name, options, &block)
begin