Provides a delegate_key
class method to easily create methods which return hash value by key.
Add this line to your application's Gemfile:
gem 'delegate_key'
And then execute:
$ bundle
Or install it yourself as:
$ gem install delegate_key
-
:to
- specifies the target object; -
:prefix
- prefixes the new method with the target name or a custom prefix; -
:private
- if set to true, changes method visibility to private.
delegate_key
method receives one or more method names (specified as symbols or strings) and the name of the target object via the :to
option (also a symbol or string).
class Foo
delegate_key :key, to: :hash
def hash
{ key: "value" }
end
end
Foo.new.key # => "value"
If hash key is a string, use string as argument:
class Foo
delegate_key "key", to: :hash
def hash
{ "key" => "value" }
end
end
Foo.new.key # => "value"
class Foo
delegate_key :key, to: :hash
def hash
{ "key" => "value" }
end
end
Foo.new.key # => nil
Multiple delegates to the same target are allowed:
class Foo
delegate_key :bar, :baz, to: :hash
def hash
{ bar: "value for bar", baz: "value for baz" }
end
end
Foo.new.bar # => "value for bar"
Foo.new.baz # => "value for baz"
Delegates can optionally be prefixed using the :prefix
option. If the value is true
, the delegate methods are prefixed with the name of the object being delegated to.
class Foo
delegate_key :key, to: :hash, prefix: true
def hash
{ key: "value" }
end
end
Foo.new.hash_key # => "value"
Foo.new.key # => NoMethodError: undefined method `key' for #<Foo:0x00007fc2452354b0>
It is also possible to supply a custom prefix:
class Foo
delegate_key :key, to: :hash, prefix: :custom
def hash
{ key: "value" }
end
end
Foo.new.custom_key # => "value"
The delegated methods are public by default. Pass private: true
to change that.
class Foo
delegate_key :key, to: :hash, private: true
def hash
{ key: "value" }
end
end
Foo.new.key # => NoMethodError: private method `key' called for #<Foo:0x00007fc24531dd28>
Bug reports and pull requests are welcome on GitHub at https://github.com/ilyasgaraev/delegate_key. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the DelegateKey project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.