https://github.com/yegor256/others
Catch all missing methods by a single proc, similar to what method_missing() is doing
https://github.com/yegor256/others
ruby ruby-gem
Last synced: 9 months ago
JSON representation
Catch all missing methods by a single proc, similar to what method_missing() is doing
- Host: GitHub
- URL: https://github.com/yegor256/others
- Owner: yegor256
- License: mit
- Created: 2024-06-24T05:28:35.000Z (about 2 years ago)
- Default Branch: master
- Last Pushed: 2024-09-17T07:44:43.000Z (almost 2 years ago)
- Last Synced: 2024-09-17T13:04:46.101Z (almost 2 years ago)
- Topics: ruby, ruby-gem
- Language: Ruby
- Homepage: https://rubygems.org/gems/others
- Size: 31.3 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 8
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# Functions as Objects, in Ruby
[](https://www.rultor.com/p/yegor256/others)
[](https://www.jetbrains.com/ruby/)
[](https://github.com/yegor256/others/actions/workflows/rake.yml)
[](https://www.0pdd.com/p?name=yegor256/others)
[](https://badge.fury.io/rb/others)
[](https://codecov.io/github/yegor256/others?branch=master)
[](https://rubydoc.info/github/yegor256/others/master/frames)
[](https://hitsofcode.com/view/github/yegor256/others)
[](https://github.com/yegor256/others/blob/master/LICENSE.txt)
Let's say you need an object that consists of a single function:
```ruby
require 'others'
x = others(foo: 42) do |*args|
@foo + args[1]
end
assert(x.bar(10) == 52)
```
You can also do this in a class:
```ruby
require 'others'
class Foo
def foo(a)
a + 1
end
others do |*args|
args[1] + 10
end
end
x = Foo.new
assert(x.foo(10) == 11)
assert(x.bar(42) == 52)
```
For example, you can create a decorator that
intercepts all method calls and logs them:
```ruby
logger = others(base: original_object) do |*args, &block|
puts "Method #{args[0]} called with #{args[1..-1].inspect}"
@base.__send__(*args, &block)
end
```
It also supports forwarding blocks:
```ruby
x = others(foo: 42) do |*args|
@foo + args.last.call # this is the block, as the last argument
end
puts x.bar { 12 } # => 54
```
## How to contribute
Read
[these guidelines](https://www.yegor256.com/2014/04/15/github-guidelines.html).
Make sure your build is green before you contribute
your pull request. You will need to have
[Ruby](https://www.ruby-lang.org/en/) 3.2+ and
[Bundler](https://bundler.io/) installed. Then:
```bash
bundle update
bundle exec rake
```
If it's clean and you don't see any error messages, submit your pull request.