Module.new with class_eval - ruby-on-rails

This is a large commit. But I want you to concentrate on this change block. http://github.com/rails/rails/commit/d916c62cfc7c59ab6411407a05b946d3dd7535e9#L2L1304
Even without understanding the full context of the code I am not able to think of a scenario where I would use
include Module.new {
class_eval <<-RUBY
def foo
puts 'foo'
end
RUBY
}
Then end result is that in the root context (self just before include Module.new) a method called foo has been added.
If I take out the Module.new code and if I only leave class_eval in that case also I will have a method called foo in self.
What am I missing.

If you dig in the documentation you find that including a module will add the methods therein only if they are not already defined. So this approach will not overwrite the method in case it is already there.

This ActiveRecord code has been asked about in another question, where it received an excellent answer. https://stackoverflow.com/a/3473479/420947
However, the simplified eval string here removes the motivation to write this code, which is why it appears confusing. In the unchanged code, the block binding captures a local variable used to reflect on the association: #{reflection.name}.clear.

Related

RIght way of writing module methods in Ruby

what is right way of writing module? is it only used to stock some peace of code to minimize the number of lines, or is it something much more important than that
I have used and seen ways of writing module, I am working on setting up correct way to define and standardised module. this example is kind of controller code that we use in rails
Way 1 :-
module B
extend ActiveSupport::Concern
def process_items
# do somthing...
#items.pluck(:names)
end
end
Class A
include B
def index
#items = Item.all
#item_names = process_items
end
end
Way 2 :-
module B
extend ActiveSupport::Concern
def process_items(items)
# do somthing...
items.pluck(:names)
end
end
Class A
include B
def index
#items = Item.all
#item_names = process_items(#items)
end
end
Way 1 :-
When I see this independently, its not much readable as I don't know how #items appeared in this method
Unit testing would be hard for method as its dependent
Way 2 :-
Looking at method I can see input is coming we are processing it and returning it back (readablity is good)
Unit testing is easy to this, we wll call method pass what it needs and expect
The way I see modules should be independent, self explanatory, it should be generic so that can be used in any class, kind of helpers. But other way could be dependent on where we use modules
We are using modules like in rails
We use conccern in models, when we call module method we can use self.<field> we don't need to pass anything because instance variable is supposed to be accesssable in every instance method
View helpers are modules I see they put logic into it hard to understand how the variable come from may be instance variable or params, what about making it method which accept somthing and return it back
Concerns on controllers, like the example I have given
I would like to have thoughts on this, what is best approach out of it? is it something which can be standarise or it is more situational or I don't know yet :)
Note: -
I was looking at this question but answer given on this question is no more valid as referenced links are not working.
Right Way to Use Module
The difference here is practically academic, as if you have attr_reader :x then both #x and x will have the same meaning.
It's understood that within a mixin module you will be referencing methods and/or variables that are part of the class or module doing the "mixing in". As such, seeing #x, or in your case, #items, should not come as a real surprise.
If you want to add it as an explicit argument you're sort of missing a lot of the benefits of using a mixin in the first place. You don't need to mix it in at all, you can just use it like B.process_items(...). In other words, your second approach is having an identity crisis. Is it a stand-alone module that includes Concern for no reason, or a weak mixin?
When it comes to testing, you must test the mixin in a module or class which implements the required features. In this case you need either an #items variable, or an items method, and that must have a value of the expected type.
This should be documented somewhere for clarity, but is effectively an implicit contract with anyone using this module.

Why isn't the args parameter used in ActionController::Instrumentation::render?

I am new to Ruby and to Rails, and am trying to understand fully what I'm reading.
I am looking at some of the Rails source code, in this case action_controller/metal/instrumentation.rb.
def render(*args)
render_output = nil
self.view_runtime = cleanup_view_runtime do
Benchmark.ms { render_output = super }
end
render_output
end
I understand that *args is using the splat operator to collect the arguments together into an array. But after that, it stops making much sense to me.
I can't fathom why render_output is set to nil before being reassigned to equal super and then called with no arguments. I gather that some speedtest is being done, but coming from other languages I'd expect this to just be something more like Benchmark.ms(render_output) or perhaps Benchmark.start followed by render_output followed by Benchmark.end. I'm having a hard time following the way it works here.
But more importantly, I don't really follow why args isn't used again. Why bother defining a param that isn't used? And I mean, clearly it is getting used-- I just don't see how. There's some hidden mechanism here that I haven't learned about yet.
In this context, it is important to note how super works, because in some cases it passes implicitly arguments and you might not expect that.
When you have method like
def method(argument)
super
end
then super is calling the overridden implementation of method implicitly with the exact same arguments as the current method was called. That means in this example super will actually call super(argument).
Of course, you can still define a method call that explicitly sends other arguments to the original implementation, like in this example:
def method(argument)
super(argument + 1)
end
Another important edge-case is when you want to explicitly call super without any arguments although the current method was called with arguments then you need to be very explicit like this
def method(argument)
super() # note the empty parentheses
end
Let me try to describe you what I think this code does.
*args*
is using the splat operator to collect the arguments together into an array
that is totally correct, however they don't use it, and if you will go to master branch, they just changed it to *. Asking why it is defined and not used, I think that's question about bad design. They should have called it _args or at least like it is now just single splat *.
render_output is set to nil because of scopes, it has to be explicitly defined out block, lambda, proc in order to store value in it, otherwise its visibility will be locked only to those lambda, proc, block execution. Refer to this article
Benchmark.start. Blocks are great ruby construction. You are totally correct that speedtest is done, we can see it is just decorator for benchmark library.
source.
You are wondering why we cannot just pass it as Benchmark.ms(render_output), that's because what will be given to benchmark ms function? It will be given result, like <div> my html </div. And how we can measure this string result - no how. That's why we calling super right in this block, we want to access parent class function and wrap it inside block, so we are not calling it, we just construct it, and it will be called inside benchmark lib, and measured execution like
class Benchmark
...
def realtime # :yield:
r0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
yield
Process.clock_gettime(Process::CLOCK_MONOTONIC) - r0
end
...
end
So here we can count realtime of function execution, this is the code from original library

rspec: Helpers Method on Model undefined method

I'm getting an issue with helpers method included in my model.
I include my helpers as follow:
class Booking < ApplicationRecord
include BookingsHelper
include PaymentsHelper
Both of BookingsHelper and PaymentsHelper have slack_notify function.
So in order to call the good slack_notify function I call this function as below:
BookingsHelper.slack_notify(self)
PaymentsHelper.slack_notify(requester.email, 'danger', 'booking:proceed_payment', e.message)
When I run my test (with rspec) I got:
Failure/Error: BookingsHelper.slack_notify(self)
NoMethodError:
undefined method `slack_notify' for BookingsHelper:Module
And I noticed if I change: BookingsHelper.slack_notify(self) by slack_notify(self) it works but call the slack_notify in PaymentsHelper so I don't really understand what's happening. And if I remove the PaymentHelper it call the good one
If someone could highlight me on this behavior, I would be really interested to understand whats going on
Thanks
You are using Mixin here.
A mixin can basically be thought of as a set of code that can be added
to one or more classes to add additional capabilities without using
inheritance. In Ruby, a mixin is code wrapped up in a module that a
class can include or extend
You do not access helper methods like the static methods but you call them directly, in your example you should call slack_notify directly without having module name before.
When you include two modules which have the same method name then the last one overrides the previous one.
If you do not want it to be overriden then you have to define in the module like that:
def BookingsHelper.slack_notify
// your code
end
and
def PaymentsHelper.slack_notify
// your code
end
see the example about sin and cos here: https://www.tutorialspoint.com/ruby/ruby_modules.htm
Read more about mixins and you will have better understanding of what is going on here.

Ruby error - Undefined Method

I am try to write a function that will find the items in an array which match the string passed to the function. See code below.
class Island
def filter(string)
for element in self
if element.include? (string)
yield(element)
end
end
end
end
list = ["sasha","rory","rob","anthony","andre","tariq","kimberly","antoinette"]
list.filter("an"){|i| puts i}</i>
How i keep getting "undefined method 'filer' for #
I'm not sure what i'm doing wrong.
First let me object against the solution posted by #Sravan :
While it is true - and sometimes even a good solution - to monkey-patch a class, you have to be careful how to do it, because it may become a time bomb:
Ruby evolves, and new versions often add methods to existing classes. This means that if you add a method Array#search, and a new version of Ruby will also add a method of the same name, your new method will SILENTLY override the one in Ruby. You likely won't notice it for long time, until you are using a feature which is supposed to use Rubys Array#search - maybe by using something new in stdlib - and you get weird results. To track down this type of error can be a nightmare. This is exactly the case when you use search as a method name.
Now, how to do it then? Three possibilities:
(1) If you monkey-patch, use at least a method name which is unlikely to become part of the official interface. It might have your project's name as a prefix, or plenty of underscore characters, and so on. Note that this is not 100% foolproof: A later version of Ruby might add under the hood a private method with exactly the same name than the one you were choosing, but of course the odder your name, the less likely this will happen.
(2) If you don't like this idea of using "clumsy" names, you could at least test before defining the new method, whether it already exists, and throw an exception if it doesn't:
class Array
if self.method_defined?(:search)
raise "#{self.class}::search already defined"
else
def search(...)
...
end
end
end
(3) The third possibility is to avoid monkey-patching and keep the method in your Island class. In this case, the method definition would be different:
class Island
def self.filter(array, string)
...
end
end
and it would be called by
Island.filter(myarray, mystring)
UPDATE: Forgot a forth possibility:
(4) You can make Island a subclass of Array. I don't know what else you want to do with your islands, but maybe this is an option worth considering:
class Island < Array
def filter(string)
...
end
end
Of course, when invoking filter, you need to turn your array into an island, before you can use it:
list = Island.new([....])
Following ruby's convention over configuration, you can add/overwrite any method in any class
So, adding a function to array class makes it accessible to all the arrays. So, in this solution.
1) First thing is you have taken the filter function in Island class, instead, you need to take inside Array class since the list is an array.
class Array
def filter(string)
for element in self
if element.include? (string)
yield(element)
end
end
end
end
list = ["sasha","rory","rob","anthony","andre","tariq","kimberly","antoinette"]
list.filter("an"){|i| puts i}
O/P:
anthony
andre
antoinette
2) Since Filter is a keyword as suggested by other answer, take another name for it. Eg: search
class Array
def search(string)
for element in self
if element.include? (string)
yield(element)
end
end
end
end
list.search("an"){|i| puts i}

how does this ruby code work for setting configuration

I see ruby code that looks like the following. It seems to be some sort of idiom for creating configuration or settings but I don't really understand it. Also, how would the Application.configure part of this code look?
MyApp::Application.configure do
config.something = foo
config.....
config....
.
config....
end
First of all, that configuration way is not specific to Ruby ; it's the applications (or libraries, gems) that choose to use it or not.
To explain you what does that code do, I'll take your snippet as an example:
MyApp::Application.configure do
config.something = foo
end
Here, you are calling MyApp::Application.configure method, with no parameter. After the call, you're giving it a block.
You can think of blocks as a piece of code that you can use however you want.
They can be written in one single line or many:
{ puts 'hello' }
{ |param| puts param } # with passing it a param
# or
do |param|
puts param
end
(remember my_array.each do ... end? It's a block you pass it. ;) )
Now, that block would be called inside the configure method thanks to yield.
yield uses (or executes) the instructions of the block that has been passed to the method.
Example: Let's define a method with a yield inside of it:
def hello
puts "Hello #{yield}"
end
If you call this method, you'd get a 'hello': no block given (yield) (LocalJumpError)'.
You need to pass it a block: hello { :Samy }.
The result would then be Hello Samy. As you can see, it simply used what was in the block passed to the method.
That's exactly what's happening in the Rails configuration code. You simply set config.something (config is a method) to some value, and that same config.something = foo is execute inside configure.
You can learn more about yield and blocks here, and on this great book.
The part from "do" until "end" is called a block, and is getting passed to the configure class method on Application. (all ruby methods can accept arguments and a block)
so the Application.configure method is creating a configuration object with a set of defaults, and then calling the block. The block is then setting the values you see, having the effect of overriding them.
It's then setting that configuration object as a class variable (like a global variable) so that other classes can use the configuration object later in the application lifecycle.
Hope that simplified description helps!

Resources