Skip to content

Commit

Permalink
add Hash method compat layer
Browse files Browse the repository at this point in the history
  • Loading branch information
svenfuchs committed Oct 6, 2015
1 parent fe01837 commit 5833cdf
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/hashr.rb
@@ -1,5 +1,7 @@
require 'hashr/core_ext/ruby/hash'

class Hashr < BasicObject
require 'hashr/core_ext/ruby/hash'
require 'hashr/delegate/conditional'
require 'hashr/env'

class << self
Expand Down
13 changes: 13 additions & 0 deletions lib/hashr/delegate/conditional.rb
@@ -0,0 +1,13 @@
class Hashr
module Delegate
module Conditional
def method_missing(name, *args, &block)
if (args.any? || block) && @data.respond_to?(name)
@data.send(name, *args, &block)
else
super
end
end
end
end
end
48 changes: 48 additions & 0 deletions lib/hashr/delegate/hash.rb
@@ -0,0 +1,48 @@
class Hashr
module Delegation
module Hash
METHODS = [
:all?,
:any?,
:clear,
:delete,
:delete_if,
:detect,
:drop,
:drop_while,
:each,
:empty?,
:fetch,
:find,
:flat_map,
:grep,
:group_by,
:hash,
:inject,
:invert,
:is_a?,
:keep_if,
:key,
:key?,
:keys,
:length,
:map,
:merge,
:nil?,
:none?,
:one?,
:reduce,
:reject,
:select,
:size,
:value?,
:values,
:values_at
]

METHODS.each do |name|
define_method(name) { |*args, &block| @data.send(name, *args, &block }
end
end
end
end
19 changes: 19 additions & 0 deletions spec/hashr/delegate/conditional_spec.rb
@@ -0,0 +1,19 @@
describe Hashr::Delegate::Conditional do
let(:klass) { Class.new(Hashr) { include Hashr::Delegate::Conditional } }

it 'delegates key?' do
hashr = klass.new(foo: 'foo')
expect(hashr.key?(:foo)).to eq(true)
end

it 'delegates select' do
hashr = klass.new(foo: 'foo', bar: 'bar')
expect(hashr.select { |key, value| key == :bar }.to_h).to eq(bar: 'bar')
end

it 'delegates delete' do
hashr = klass.new(foo: 'foo', bar: 'bar')
hashr.delete(:foo)
expect(hashr.to_h).to eq(bar: 'bar')
end
end

0 comments on commit 5833cdf

Please sign in to comment.