Posts

Showing posts from June, 2016

using yield and content for in a partial

Time comes in your development process when you want one partial for two action with some changes in a section of html. In that case usually developers prefer to opt for if else or creating another partial or the whole new html template but all of them are good but not being rubyist style. To achieve that you can use yield and content_for for example : suppose you do have a partial _a.html.erb with some html in it <div class='main'> <p> this is main section</p> <div class = 'subpart'> <p> this is subpart </p> </div> <div class="block_of_code"> <%= yield :block_of_code %> </div> </div> In this block of code div you want to replace it with your block of code using same partial but with different block of code . So here I have used yield :block of code and now you can use content for rendering different block of code for different actions. for example you do have two action

define_method in ruby

So one more step close to meta programming define_method. The usual way of defining new methods is to put your intended logic between def & end . And that works perfectly fine for the most part. But consider a situation where you have to create a series of methods all of which have the same basic structure save for one string, and which can only be one of a certain set of strings. Now, you might say we'll just define one method and accept that one string as a parameter, which we can then use wherever we want. And you'd be right. But, the problem with such an approach is it's not particularly declarative: you don't know exactly what values that optional parameter can accept.   class DefineMethod      define_method("perform_chunk") do |argument|          "performing chunk on #{argument}"      end      define_method("perform_chomp") do |argument|          "performing chomp on #{argument}"      end  end  d= Defi