Proc.new binding change and loops logic abstraction - ruby

I've two loops in two different methods which look very similar. I wanted to abstract most of their logic in a Proc.new
This works
def matches_base?
proc_exec = Proc.new do |subclass, breakpoint|
# next and return are meant to act inside the loop and quit it if needed
response = process_match(subclass)
next if response == :continue
return true if response == false
return response
end
subclasses(BASE_NAMESPACE).each do |subclass|
proc_exec.call(subclass)
end
false
end
The obvious issue here is the proc_exec is defined inside the method itself, but I want to use it in another method
def matches_breakpoints?
breakpoints.fetch.each do |breakpoint|
# I want to include the proc_exec here too
end
false
end
So I just tried to extract it at the class level like so
This does not work
def proc_exec
Proc.new do |subclass, breakpoint|
response = process_match(subclass)
next if response == :continue
return true if response == false
return response
end
end
def matches_base?
subclasses(BASE_NAMESPACE).each do |subclass|
proc_exec.call(subclass)
end
false
end
Then I could have called it like proc_exec.call from within both instance methods. Currently it throws
LocalJumpError:
unexpected return
I tried many tricks such as instance_eval or instance_exec without success. I'm out of solution right now.
Easily executable, simplified example of what I want below.
class MyLoops
def proc_exec
Proc.new do |num|
next if num == 1
# we want this `return` to act in the method context
# as it would do if I defined it inside a method directly
return if num == 4
puts "Current number : #{num}"
end
end
def method_a
[0,1,2].each do |num|
proc_exec.call(num)
end
false
end
def method_b
[3,4,5].each do |num|
proc_exec.call(num)
end
end
# this `false` below should never be reached ; that's the trick
false
end
loops = MyLoops.new
loops.method_a
loops.method_b

You can't have your cake and eat it too. If you want return from the proc to abort the method, it must be in the method's lexical scope* (which is another way to say "it must be defined within the same method").
An alternative is to have proc/lambda return a "stop" value, which caller will use to abort its execution.
(Your experiments with instance_eval/instance_exec were misdirected, sadly. Those methods only change current self. This problem has nothing to do with current self, but rather current lexical scope, in which return is executed.)
* The error you're getting, it is caused by return trying to return from a method that is no longer running (proc_exec).

Related

Understanding the control flow using `each` and `yield`

I came across this code:
class RandomSequence
def initialize(limit,num)
#limit,#num = limit,num
end
def each
#num.times { yield (rand * #limit).floor }
end
end
i = -1
RandomSequence.new(10,4).each do |num|
i = num if i < num
end
Is it the case that the each method is called only once and will compute four different values, and then for each of those values we execute code block between do and end? Is my understanding of control flow correct?
Your understanding is close. The random number will be generated, then a block yielded, then another generated, etc 4 times. You can verify this easily by adding puts statements into you blocks to see when they are executed.
class RandomSequence
def initialize(limit,num)
#limit,#num = limit,num
end
def each
puts "in each"
#num.times { yield (rand.tap {|x| puts "Generated #{x}" } * #limit).floor }
end
end
i = -1
RandomSequence.new(10,4).each do |num|
puts "in block"
i = num if i < num
end
Outputs
in each
Generated 0.6724385316643955
in block
Generated 0.8906983274750662
in block
Generated 0.49038868732214036
in block
Generated 0.38100454011243456
in block
The each method on the RandomSequence class is called once. In it #num.times which creates an Enumerator. The Enumerator is iterated over and the block with the yield statement is called (with the argument to it ignored).
The yield statement calls the block that's passed to the each method passing the value of (rand * #limit).floor. In your code the block is not bound to a variable, i.e you could get a reference to the block by doing:
def each(&block)
#... do stuff with block, e.g. block.call("some args")
end
which can be useful at times.
A bit off topic, but one thing I found scary with Ruby starting out is that a return statement returns the flow of execution from where it was defined.
def create_proc
puts "Creating proc"
Proc.new do
puts "In proc!"
return "some value" # notice the explicit return
end
end
def do_stuff
my_proc = create_proc
my_proc.call # This will cause a runtime error
end
If the explicit return is removed everything works there is no error... Lesson being that in ruby you should probably avoid using explicit returns.

Can I get the return value inside 'ensure' in Ruby?

def some_method
puts 'in method'
return 'I am a return value'
ensure
puts 'will print at the end'
# Can I somehow get the return value of some_method here?
end
Is there some (possibly meta-programming) principle/way to get the return value of a method inside the "ensure" clause which is a part of the method definition (which we all know executes no matter what)?
Assign a Variable
Just make your return value a variable. You can use the variable inside your ensure statement, but the return value for the method will be the last statement evaluated in the non-exceptional part of the method. For example:
def some_method
puts 'in method'
value = 'I am a return value'
ensure
puts 'will print at the end'
puts value
true
end
some_method
#=> "I am a return value"
Early Returns Work the Same
Note that the technique above works even if you return early, since the value passed to the return keyword is still the last non-exceptional expression evaluated. For example, the following method should never return false:
def return_true
return value = true
false
ensure
puts value
false
end
return_true
#=> true
Why do you need this in ensure? If the main part of the method completed w/o exception the return value of that part will be returned from the method (unless you do return in ensure). If exception happens, the return in your main part is not calculated at all.
Of course you can always use the following (very ugly IMO) code. But please don't do that. A better idea is to leave only the resource-cleanup code in the ensure block.
def some_method
finished = false
begin
puts 'in method'
result = 'I am a return value'
finished = true
ensure
puts 'will print at the end'
# Do whatever is needed for cleanup
if finished
# Here result is defined, you can manipulate it if needed
return result
end
end
end

How to get the return value of the block passed to eval method?

I want to implement something like a sandbox which can
eval given string
execute given block in the same context with eval
return the result of block
The aim of the sandbox is to inspect the contents - functions, variables, e.t.c. - of vulnerable codes.
Here is my spec
it 'returns return value of given block' do
value = Sandbox.secure_eval('hoge = ["hoge", "fuga"]') do
hoge[0]
end
expect(value).to eq('hoge')
end
and, this is my implementation of sandbox
require 'timeout'
module Sandbox
def self.secure_eval(code, timeout: 5, safe_level: 2)
raise ArgumentError, 'please set call back by block' unless block_given?
proc = Proc.new do
Timeout::timeout timeout do
$SAFE = safe_level
eval code do
yield
end
end
end
proc.call
end
end
But #secure_eval returns the result of eval, in this case ["hoge", "fuga"], and cannot capture the return value of the block.
How can I make it?
You can return the result of eval to the block using yield. You just had to yield the value; thus I changed your yield to yield eval code. In the block you give to Sandbox.secure_eval you have to then bind this result to a block variable. The result of secure_eval will be the result of the block, like you wanted.
proc = Proc.new do
Timeout::timeout timeout do
$SAFE = safe_level
yield eval code # <= This line changed
end
end
Sandbox.secure_eval('hoge = ["hoge", "fuga"]') { |hoge| hoge[0] }
# => "hoge"
Sandbox.secure_eval('2 ** 4') { |result| result - 5 }
# => 11
In response to your comment; it turns out that with the aid of Kernel#Binding, we can get it to work more or less like you wanted. It feels rather like a hack so use it with caution.
I use the Binding to evaluate the code, which will have access to all defined variables. In addition, I define a method_missing for the Binding class so we can access the variables more easily. Without it, you would need to do eval('varname') rather than just varname. Per the comment of #hakcho who mentioned the monkey-patch solution that was in place is not ideal, I now use refinements which only locally changes the behavior of Binding (i.e., the method_missing implementation).
I have added an explicit block parameter to your method, which I use with instance_eval instead of yield. We can then access the variables directly in the block.
require 'timeout'
module Sandbox
refine Binding do
def method_missing(meth, *args, &block)
self.eval(meth.to_s)
end
end
def self.secure_eval(code, timeout: 5, safe_level: 2, &block)
raise ArgumentError, 'please set call back by block' unless block_given?
proc = Proc.new do
Timeout::timeout timeout do
$SAFE = safe_level
binding = binding()
binding.eval(code)
binding.instance_eval(&block)
end
end
proc.call
end
end
using Sandbox # Activate the refinement so we can use x, y, z directly
Sandbox.secure_eval('x = [1,2,3]; y = 0; z = { key: "Hello!" }') do
x[1] # => 2
y # => 0
z[:key] # => "Hello!"
end

Ruby nil-like object

How can I create an Object in ruby that will be evaluated to false in logical expressions similar to nil?
My intention is to enable nested calls on other Objects where somewhere half way down the chain a value would normally be nil, but allow all the calls to continue - returning my nil-like object instead of nil itself. The object will return itself in response to any received messages that it does not know how to handle and I anticipate that I will need to implement some override methods such as nil?.
For example:
fizz.buzz.foo.bar
If the buzz property of fizz was not available I would return my nil-like object, which would accept calls all the way down to bar returning itself. Ultimately, the statement above should evaluate to false.
Edit:
Based on all the great answers below I have come up with the following:
class NilClass
attr_accessor :forgiving
def method_missing(name, *args, &block)
return self if #forgiving
super
end
def forgive
#forgiving = true
yield if block_given?
#forgiving = false
end
end
This allows for some dastardly tricks like so:
nil.forgiving {
hash = {}
value = hash[:key].i.dont.care.that.you.dont.exist
if value.nil?
# great, we found out without checking all its parents too
else
# got the value without checking its parents, yaldi
end
}
Obviously you could wrap this block up transparently inside of some function call/class/module/wherever.
This is a pretty long answer with a bunch of ideas and code samples of how to approach the problem.
try
Rails has a try method that let's you program like that. This is kind of how it's implemented:
class Object
def try(*args, &b)
__send__(*a, &b)
end
end
class NilClass # NilClass is the class of the nil singleton object
def try(*args)
nil
end
end
You can program with it like this:
fizz.try(:buzz).try(:foo).try(:bar)
You could conceivably modify this to work a little differently to support a more elegant API:
class Object
def try(*args)
if args.length > 0
method = args.shift # get the first method
__send__(method).try(*args) # Call `try` recursively on the result method
else
self # No more methods in chain return result
end
end
end
# And keep NilClass same as above
Then you could do:
fizz.try(:buzz, :foo, :bar)
andand
andand uses a more nefarious technique, hacking the fact that you can't directly instantiate NilClass subclasses:
class Object
def andand
if self
self
else # this branch is chosen if `self.nil? or self == false`
Mock.new(self) # might want to modify if you have useful methods on false
end
end
end
class Mock < BasicObject
def initialize(me)
super()
#me = me
end
def method_missing(*args) # if any method is called return the original object
#me
end
end
This allows you to program this way:
fizz.andand.buzz.andand.foo.andand.bar
Combine with some fancy rewriting
Again you could expand on this technique:
class Object
def method_missing(m, *args, &blk) # `m` is the name of the method
if m[0] == '_' and respond_to? m[1..-1] # if it starts with '_' and the object
Mock.new(self.send(m[1..-1])) # responds to the rest wrap it.
else # otherwise throw exception or use
super # object specific method_missing
end
end
end
class Mock < BasicObject
def initialize(me)
super()
#me = me
end
def method_missing(m, *args, &blk)
if m[-1] == '_' # If method ends with '_'
# If #me isn't nil call m without final '_' and return its result.
# If #me is nil then return `nil`.
#me.send(m[0...-1], *args, &blk) if #me
else
#me = #me.send(m, *args, &blk) if #me # Otherwise call method on `#me` and
self # store result then return mock.
end
end
end
To explain what's going on: when you call an underscored method you trigger mock mode, the result of _meth is wrapped automatically in a Mock object. Anytime you call a method on that mock it checks whether its not holding a nil and then forwards your method to that object (here stored in the #me variable). The mock then replaces the original object with the result of your function call. When you call meth_ it ends mock mode and returns the actual return value of meth.
This allows for an api like this (I used underscores, but you could use really anything):
fizz._buzz.foo.bum.yum.bar_
Brutal monkey-patching approach
This is really quite nasty, but it allows for an elegant API and doesn't necessarily screw up error reporting in your whole app:
class NilClass
attr_accessor :complain
def method_missing(*args)
if #complain
super
else
self
end
end
end
nil.complain = true
Use like this:
nil.complain = false
fizz.buzz.foo.bar
nil.complain = true
As far as I'm aware there's no really easy way to do this. Some work has been done in the Ruby community that implements the functionality you're talking about; you may want to take a look at:
The andand gem
Rails's try method
The andand gem is used like this:
require 'andand'
...
fizz.buzz.andand.foo.andand.bar
You can modify the NilClass class to use method_missing() to respond to any
not-yet-defined methods.
> class NilClass
> def method_missing(name)
> return self
> end
> end
=> nil
> if nil:
* puts "true"
> end
=> nil
> nil.foo.bar.baz
=> nil
There is a principle called the Law of Demeter [1] which suggests that what you're trying to do is not good practice, as your objects shouldn't necessarily know so much about the relationships of other objects.
However, we all do it :-)
In simple cases I tend to delegate the chaining of attributes to a method that checks for existence:
class Fizz
def buzz_foo_bar
self.buzz.foo.bar if buzz && buzz.foo && buzz.foo.bar
end
end
So I can now call fizz.buzz_foo_bar knowing I won't get an exception.
But I've also got a snippet of code (at work, and I can't grab it until next week) that handles method missing and looks for underscores and tests reflected associations to see if they respond to the remainder of the chain. This means I don't now have to write the delegate methods and more - just include the method_missing patch:
module ActiveRecord
class Base
def children_names
association_names=self.class.reflect_on_all_associations.find_all{|x| x.instance_variable_get("#macro")==:belongs_to}
association_names.map{|x| x.instance_variable_get("#name").to_s} | association_names.map{|x| x.instance_variable_get("#name").to_s.gsub(/^#{self.class.name.underscore}_/,'')}
end
def reflected_children_regex
Regexp.new("^(" << children_names.join('|') << ")_(.*)")
end
def method_missing(method_id, *args, &block)
begin
super
rescue NoMethodError, NameError
if match_data=method_id.to_s.match(reflected_children_regex)
association_name=self.methods.include?(match_data[1]) ? match_data[1] : "#{self.class.name.underscore}_#{match_data[1]}"
if association=send(association_name)
association.send(match_data[2],*args,&block)
end
else
raise
end
end
end
end
end
[1] http://en.wikipedia.org/wiki/Law_of_Demeter

How to create a method like ".find_by_something_and_something_else" using Ruby?

Using Ruby I know you can get pretty creative with how you name your methods. For instance in rails you have .find_by_this_and_that.
How can I do this?
Example:
def get_persons_with_5_things
res = []
persons.each do |person|
if person.number_of_things == %MAGICALLY GET THE NUMBER 5 FROM FUNCTION NAME%
res << person
end
end
return res
end
I'm not even sure how you call this kind of things so any pointers would be appreciated.
I'm a little confused by your example. If you define the method with the hardcoded 5 in the method name, then you don't need to magically figure it out inside the body of the method. If you want to do something dynamic with method missing, it would be something like this:
def method_missing(name, *args)
if name.to_s =~ /get_persons_with_(\d+)_things/
number_of_things = $1.to_i
res = []
persons.each do |person|
if person.number_of_things == number_of_things
res << person
end
end
return res
else
return super(name, *args)
end
end
[EDIT (Jörg W Mittag)]: This is a more Rubyish way of implementing that same method:
def method_missing(name, *args)
return super unless name.to_s =~ /get_persons_with_(\d+)_things/
number_of_things = $1.to_i
return persons.select {|person| person.number_of_things == number_of_things }
end
super without any arguments just passes the original arguments along, no need to pass them explicitly
an early return guarded by a trailing if or unless expression greatly clears up control flow
all the each iterator does, is select items according to a predicate; however, there already is an iterator for selecting items: select
Ruby has different meta programming techniches to do this kind of stuff.
First we need our variable method
class DB
def get_persons_with_x_things(x)
res = []
persons.each do |person|
if person.number_of_things == x
res << person
end
end
return res
end
end
define_method
If there is a finite number of x's. We could use define_method to create all this methods. define_method creates a method. The first argument is the name of the method, the seccond argument or the given block is the stuff, which get's executed when the method is called.
This way, you don't realy create such method's, but It will look for the user if he calls it, as if it existed. But if the user relies on Object#methods and such, he will never see your inifinite number of fake methods.
class DB
99.times do |i|
define_method("get_persons_with_#{i}_things") do
get_persons_with_x_things(i)
end
end
end
method_missing
If there is an infinite numbor of x's method_missing would be better suited for this Task. If someone tries to call a method which does not exist, method_missing is executed instead. The first argument for method_missing is the method name as symbol, the following arguments are the original arguments.
class DB
def method_missing(name, *args)
case name.to_s
when /^get_persons_with_(\d+)_things$/
get_persons_with_x_things($1.to_i)
else
super(name, *args)
end
end
end
method_missing and send
To not use static regexe would be even cooler. But this could have some security implications. The method send I use here, calls a method by it's name.
class DB
def method_missing(name, *args)
name.to_s=~ /\d+/
# always be carefull with $ variables, they are global for this thread, so save everything as fast as you can
new_name= "#{$`}x#{$'}"
number= $1.to_i
if method_defined?(new_name)
send(new_name, number)
else
super(name, *args)
end
end
end
you can do a lot of things like this with method missing:
Ruby Docs
StackOveflow method_missing
Have a look at Ruby's callbacks specially method_missing.

Resources