<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.jacopobeschi.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.jacopobeschi.com/" rel="alternate" type="text/html" /><updated>2025-10-06T15:15:03+00:00</updated><id>https://www.jacopobeschi.com/feed.xml</id><title type="html">Jacopo Beschi 👋</title><subtitle>Ruby and Ruby on Rails web development tips, but also PHP, Laravel and OOP programming.</subtitle><entry><title type="html">What is Ruby String.length time complexity?</title><link href="https://www.jacopobeschi.com/ruby/2021/01/27/ruby-string-length-time-complexity.html" rel="alternate" type="text/html" title="What is Ruby String.length time complexity?" /><published>2021-01-27T22:30:00+00:00</published><updated>2021-01-27T22:30:00+00:00</updated><id>https://www.jacopobeschi.com/ruby/2021/01/27/ruby-string-length-time-complexity</id><content type="html" xml:base="https://www.jacopobeschi.com/ruby/2021/01/27/ruby-string-length-time-complexity.html"><![CDATA[<p>I’ve been asking myself this question: is Ruby <code class="language-plaintext highlighter-rouge">String.length</code> like C <code class="language-plaintext highlighter-rouge">strlen</code> which is <code class="language-plaintext highlighter-rouge">O(n)</code>? In order to find it I’ve decided to dive into the
Ruby MRI source code (which is written in C).</p>

<p>Here’s the source code of ruby <code class="language-plaintext highlighter-rouge">String.length</code> (at the time of writing this article):</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">VALUE</span>
<span class="nf">rb_str_length</span><span class="p">(</span><span class="n">VALUE</span> <span class="n">str</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="n">LONG2NUM</span><span class="p">(</span><span class="n">str_strlen</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">));</span>
<span class="p">}</span>
</code></pre></div></div>

<p>As you can see it a calls <code class="language-plaintext highlighter-rouge">str_strlen</code> and then calls <code class="language-plaintext highlighter-rouge">LONG2NUM</code> on the results, what <code class="language-plaintext highlighter-rouge">LONG2NUM</code> does
is just to convert a <code class="language-plaintext highlighter-rouge">C long int</code> into a ruby <code class="language-plaintext highlighter-rouge">Numeric</code> class.
At this point let’s see what <code class="language-plaintext highlighter-rouge">str_strlen</code> does:</p>

<pre>
static long
str_strlen(VALUE str, rb_encoding *enc)
{
    const char *p, *e;
    int cr;

    <strong>if (single_byte_optimizable(str)) return RSTRING_LEN(str);</strong>
    if (!enc) enc = STR_ENC_GET(str);
    p = RSTRING_PTR(str);
    e = RSTRING_END(str);
    cr = ENC_CODERANGE(str);

    if (cr == ENC_CODERANGE_UNKNOWN) {
	long n = rb_enc_strlen_cr(p, e, enc, &amp;cr);
	if (cr) ENC_CODERANGE_SET(str, cr);
	return n;
    }
    else {
	return enc_strlen(p, e, enc, cr);
    }
}
</pre>

<p>What you should focus on is just the bold text, which is what usually runs (except if the string is encoded in a
multi-byte encoding). If you take a look all is does is to call <code class="language-plaintext highlighter-rouge">RSTRING_LEN(str)</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#define RSTRING_LEN(string) RSTRING(string)-&gt;len
</code></pre></div></div>

<p>The above is a C macro which just fetches len from a <code class="language-plaintext highlighter-rouge">RString</code> struct. In fact every Ruby string is
stored in a <code class="language-plaintext highlighter-rouge">RString</code> struct, which contains meaningful informations such as the current length of the
String:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">struct</span> <span class="n">RString</span> <span class="p">{</span>
    <span class="k">struct</span> <span class="n">RBasic</span> <span class="n">basic</span><span class="p">;</span>
    <span class="k">union</span> <span class="p">{</span>
        <span class="k">struct</span> <span class="p">{</span>
            <span class="kt">long</span> <span class="n">len</span><span class="p">;</span>
            <span class="kt">char</span> <span class="o">*</span><span class="n">ptr</span><span class="p">;</span>
            <span class="k">union</span> <span class="p">{</span>
                <span class="kt">long</span> <span class="n">capa</span><span class="p">;</span>
                <span class="n">VALUE</span> <span class="n">shared</span><span class="p">;</span>
            <span class="p">}</span> <span class="n">aux</span><span class="p">;</span>
        <span class="p">}</span> <span class="n">heap</span><span class="p">;</span>
        <span class="kt">char</span> <span class="n">ary</span><span class="p">[</span><span class="n">RSTRING_EMBED_LEN_MAX</span> <span class="o">+</span> <span class="mi">1</span><span class="p">];</span>
    <span class="p">}</span> <span class="n">as</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Now that you’ve seen how it works I think you already know the answer: the time complexity to read a
String length in ruby is <code class="language-plaintext highlighter-rouge">O(1)</code> constant time, unless we are saving a string in a multi byte
encoding which cannot benefit from the <code class="language-plaintext highlighter-rouge">single_byte_optimizable</code> feature. In that case we have a
performance degradation to <code class="language-plaintext highlighter-rouge">O(n)</code>.</p>

<p>Below some benchmarks which shows this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">require</span> <span class="s1">'benchmark/ips'</span>

<span class="n">optimizable</span> <span class="o">=</span> <span class="s2">"this is a string"</span> <span class="o">*</span> <span class="mi">10_000</span>
<span class="n">not_optimizable</span> <span class="o">=</span> <span class="s2">"this is â string"</span> <span class="o">*</span> <span class="mi">10_000</span>

<span class="no">Benchmark</span><span class="p">.</span><span class="nf">ips</span> <span class="k">do</span> <span class="o">|</span><span class="n">x</span><span class="o">|</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"optimizable"</span><span class="p">)</span> <span class="p">{</span> <span class="n">optimizable</span><span class="p">.</span><span class="nf">length</span> <span class="p">}</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">report</span><span class="p">(</span><span class="s2">"not optimizable"</span><span class="p">)</span> <span class="p">{</span> <span class="n">not_optimizable</span><span class="p">.</span><span class="nf">length</span> <span class="p">}</span>
  <span class="n">x</span><span class="p">.</span><span class="nf">compare!</span>
<span class="k">end</span>

</code></pre></div></div>

<p>result:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Calculating -------------------------------------
         optimizable   268.816k i/100ms
     not optimizable     7.570k i/100ms
-------------------------------------------------
         optimizable     28.189M (± 4.8%) i/s -    140.322M
     not optimizable     76.836k (± 5.8%) i/s -    386.070k

Comparison:
         optimizable: 28188582.0 i/s
     not optimizable:    76836.2 i/s - 366.87x slower
</code></pre></div></div>

<p>As you can see just by using a 160000 length string the optimized <code class="language-plaintext highlighter-rouge">O(1)</code> version is 366 times faster,
the longer is the string compared the faster will be the optimized version due to the different time
complexity.</p>]]></content><author><name></name></author><category term="ruby" /><summary type="html"><![CDATA[I’ve been asking myself this question: is Ruby String.length like C strlen which is O(n)? In order to find it I’ve decided to dive into the Ruby MRI source code (which is written in C).]]></summary></entry><entry><title type="html">Abstracting SQL union with ActiveRecord</title><link href="https://www.jacopobeschi.com/ruby%20on%20rails/activerecord/2020/02/20/abstracting-sql-union-with-active-record.html" rel="alternate" type="text/html" title="Abstracting SQL union with ActiveRecord" /><published>2020-02-20T18:00:00+00:00</published><updated>2020-02-20T18:00:00+00:00</updated><id>https://www.jacopobeschi.com/ruby%20on%20rails/activerecord/2020/02/20/abstracting-sql-union-with-active-record</id><content type="html" xml:base="https://www.jacopobeschi.com/ruby%20on%20rails/activerecord/2020/02/20/abstracting-sql-union-with-active-record.html"><![CDATA[<p>Sometimes you might need to use SQL UNION in your application, in this article we explan you how to
abstract SQL union creation within ActiveRecord.</p>

<p>The main idea is to create an abstaction which receives in input an array of ActiveRecord relations
and then transform the given array into SQL, eventually we’ll use <code class="language-plaintext highlighter-rouge">ActiveRecord.from</code> method in order
to load the given SQL as an ActiveRecord relation.</p>

<p>Please note that I extracted this examples from <a href="https://gitlab.com/">gitlab</a> codebase.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">module</span> <span class="nn">Gitlab</span>
  <span class="k">module</span> <span class="nn">SQL</span>
    <span class="c1"># Class for building SQL UNION statements.</span>
    <span class="c1">#</span>
    <span class="c1"># ORDER BYs are dropped from the relations as the final sort order is not</span>
    <span class="c1"># guaranteed any way.</span>
    <span class="c1">#</span>
    <span class="c1"># Example usage:</span>
    <span class="c1">#</span>
    <span class="c1">#     union = Gitlab::SQL::Union.new([user.personal_projects, user.projects])</span>
    <span class="c1">#     sql   = union.to_sql</span>
    <span class="c1">#</span>
    <span class="c1">#     Project.from("(#{union}) projects")</span>
    <span class="k">class</span> <span class="nc">Union</span>
      <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">relations</span><span class="p">,</span> <span class="ss">remove_duplicates: </span><span class="kp">true</span><span class="p">)</span>
        <span class="vi">@relations</span> <span class="o">=</span> <span class="n">relations</span>
        <span class="vi">@remove_duplicates</span> <span class="o">=</span> <span class="n">remove_duplicates</span>
      <span class="k">end</span>

      <span class="k">def</span> <span class="nf">to_sql</span>
        <span class="c1"># Some relations may include placeholders for prepared statements, these</span>
        <span class="c1"># aren't incremented properly when joining relations together this way.</span>
        <span class="c1"># By using "unprepared_statements" we remove the usage of placeholders</span>
        <span class="c1"># (thus fixing this problem), at a slight performance cost.</span>
        <span class="n">fragments</span> <span class="o">=</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span><span class="p">.</span><span class="nf">connection</span><span class="p">.</span><span class="nf">unprepared_statement</span> <span class="k">do</span>
          <span class="vi">@relations</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="o">|</span><span class="n">rel</span><span class="o">|</span> <span class="n">rel</span><span class="p">.</span><span class="nf">reorder</span><span class="p">(</span><span class="kp">nil</span><span class="p">).</span><span class="nf">to_sql</span> <span class="p">}.</span><span class="nf">reject</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:blank?</span><span class="p">)</span>
        <span class="k">end</span>

        <span class="k">if</span> <span class="n">fragments</span><span class="p">.</span><span class="nf">any?</span>
          <span class="s2">"("</span> <span class="o">+</span> <span class="n">fragments</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="s2">")</span><span class="se">\n</span><span class="si">#{</span><span class="n">union_keyword</span><span class="si">}</span><span class="se">\n</span><span class="s2">("</span><span class="p">)</span> <span class="o">+</span> <span class="s2">")"</span>
        <span class="k">else</span>
          <span class="s1">'NULL'</span>
        <span class="k">end</span>
      <span class="k">end</span>

      <span class="k">def</span> <span class="nf">union_keyword</span>
        <span class="vi">@remove_duplicates</span> <span class="p">?</span> <span class="s1">'UNION'</span> <span class="p">:</span> <span class="s1">'UNION ALL'</span>
      <span class="k">end</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>With the above class you can create very quiclky an UNION given an array of AR relations, for
example as explained in the comment you can do:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">union</span> <span class="o">=</span> <span class="no">Gitlab</span><span class="o">::</span><span class="no">SQL</span><span class="o">::</span><span class="no">Union</span><span class="p">.</span><span class="nf">new</span><span class="p">([</span><span class="n">user</span><span class="p">.</span><span class="nf">personal_projects</span><span class="p">,</span> <span class="n">user</span><span class="p">.</span><span class="nf">projects</span><span class="p">])</span>
<span class="n">sql</span>   <span class="o">=</span> <span class="n">union</span><span class="p">.</span><span class="nf">to_sql</span>

<span class="n">projects</span> <span class="o">=</span> <span class="no">Project</span><span class="p">.</span><span class="nf">from</span><span class="p">(</span><span class="s2">"(</span><span class="si">#{</span><span class="n">union</span><span class="si">}</span><span class="s2">) projects"</span><span class="p">)</span>
</code></pre></div></div>

<p>Worth noting that we are dealing always with AR relations which imples that the query is run only if
needed; this also implies that the AR relation can be used as parameter to other queries.</p>

<p>Also note that this code will run without loading data in memory (until is needed) thus the code is performant!</p>]]></content><author><name></name></author><category term="ruby on rails" /><category term="activerecord" /><summary type="html"><![CDATA[Sometimes you might need to use SQL UNION in your application, in this article we explan you how to abstract SQL union creation within ActiveRecord.]]></summary></entry><entry><title type="html">Different caching strategies for Rails.cache and ActionController::Caching</title><link href="https://www.jacopobeschi.com/ruby%20on%20rails/2017/06/19/different-caching-strategies-for-rails-cache-and-actioncontroller-caching.html" rel="alternate" type="text/html" title="Different caching strategies for Rails.cache and ActionController::Caching" /><published>2017-06-19T15:10:00+00:00</published><updated>2017-06-19T15:10:00+00:00</updated><id>https://www.jacopobeschi.com/ruby%20on%20rails/2017/06/19/different-caching-strategies-for-rails-cache-and-actioncontroller-caching</id><content type="html" xml:base="https://www.jacopobeschi.com/ruby%20on%20rails/2017/06/19/different-caching-strategies-for-rails-cache-and-actioncontroller-caching.html"><![CDATA[<p>If you need to use different caching strategies for your Rails.cache and your ActionController::Cache (used for fragment caching) just put the following in your <code class="language-plaintext highlighter-rouge">config/environments/env.rb</code> file:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>     config.action_controller.perform_caching = true
     # this is used for your Fragment cache
     config.action_controller.cache_store = :file_store, 'action_controller_tore_path'
     # this is used for Rails.cache
     config.cache_store = :file_store, 'cache_store_path'
</code></pre></div></div>]]></content><author><name></name></author><category term="ruby on rails" /><summary type="html"><![CDATA[If you need to use different caching strategies for your Rails.cache and your ActionController::Cache (used for fragment caching) just put the following in your config/environments/env.rb file:]]></summary></entry><entry><title type="html">Thinner Rails Model with the Finder Pattern</title><link href="https://www.jacopobeschi.com/design%20pattern/ruby/ruby%20on%20rails/2017/03/20/thinner-rails-model-with-the-finder-pattern.html" rel="alternate" type="text/html" title="Thinner Rails Model with the Finder Pattern" /><published>2017-03-20T09:17:00+00:00</published><updated>2017-03-20T09:17:00+00:00</updated><id>https://www.jacopobeschi.com/design%20pattern/ruby/ruby%20on%20rails/2017/03/20/thinner-rails-model-with-the-finder-pattern</id><content type="html" xml:base="https://www.jacopobeschi.com/design%20pattern/ruby/ruby%20on%20rails/2017/03/20/thinner-rails-model-with-the-finder-pattern.html"><![CDATA[<p>Hello everybody, today I want to share with you a pattern learned from <strong>gitlab</strong>: the <strong>finder</strong> pattern.</p>

<p>Most of the time when you want to find an item based on a set of different conditions you do something like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>class Project
  		def issues_for_user_filtered_by(user, filter)
		# A lot of logic not related to project model itself
  		end
end
</code></pre></div></div>

<p>By doing that you end up having a lot of methods that does not really belong to the Model logic.
A better solution is through the <strong>finder</strong> pattern:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>issues = IssuesFinder.new(project, user, filter).execute
</code></pre></div></div>

<p>What the finder does is to accept a set of parameters and return an <code class="language-plaintext highlighter-rouge">ActiveRecord::Associations::CollectionProxy</code> that you can use for further filtering/mapping operations.</p>

<p>You can find a complete example of a finder <a href="https://gitlab.com/gitlab-org/gitlab-ce/blob/master/app/finders/issuable_finder.rb">following this link</a></p>]]></content><author><name></name></author><category term="design pattern" /><category term="ruby" /><category term="ruby on rails" /><summary type="html"><![CDATA[Hello everybody, today I want to share with you a pattern learned from gitlab: the finder pattern.]]></summary></entry><entry><title type="html">Javascript multiple inheritance with ES5 and AngularJs</title><link href="https://www.jacopobeschi.com/design%20pattern/javascript/2016/03/31/javascript-multiple-inheritance-with-es5-and-angularjs.html" rel="alternate" type="text/html" title="Javascript multiple inheritance with ES5 and AngularJs" /><published>2016-03-31T12:55:00+00:00</published><updated>2016-03-31T12:55:00+00:00</updated><id>https://www.jacopobeschi.com/design%20pattern/javascript/2016/03/31/javascript-multiple-inheritance-with-es5-and-angularjs</id><content type="html" xml:base="https://www.jacopobeschi.com/design%20pattern/javascript/2016/03/31/javascript-multiple-inheritance-with-es5-and-angularjs.html"><![CDATA[<p>In this article I’ll show you how you can use multiple inheritance(trait) with Javascript EcmaScript 5 and AngularJS 1.0.
AngularJS offer you a method: <em>angular.extend</em> that allow you to extend any object with the values and methods of other objects.
In this article I show you how you can create a Dog. Dog is an animal but is also a mammal, for this reason a Dog needs to extend animal and also Mammal classes.
Below is the code to create a Dog:</p>

<!-- more -->

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(function(){
app.Animal = function(){};
app.Animal.prototype = {
	animal: function(){
		return "Hello i am an animal";
	}
};

app.Mammal = function(){};
app.Mammal.prototype = {
	mammal: function(){
		return "I am a mammal";
	}
};

app.Dog = function(){};
app.Dog.prototype = {
	dog: function () {
		return "I am a dog";
	}
};
// dog is an animal but also a mammal
angular.extend(app.Dog.prototype, app.Animal.prototype, app.Mammal.prototype);
// wrap to not pollute the global namespace
})(window.app || (window.app ={}));

var dog = new app.Dog();

// Hello I am an animal
console.info(dog.animal());
// Hello I am a mammal
console.info(dog.mammal());
// Hello I am a dog
console.info(dog.dog());
</code></pre></div></div>

<p>As you can see you can extend multiple classes (Mammal and Animal) from the Dog class.
Here it is! Now you know that you can easily implement traits in Javascript using angular.extend() method.
Happy coding!</p>]]></content><author><name></name></author><category term="design pattern" /><category term="javascript" /><summary type="html"><![CDATA[In this article I’ll show you how you can use multiple inheritance(trait) with Javascript EcmaScript 5 and AngularJS 1.0. AngularJS offer you a method: angular.extend that allow you to extend any object with the values and methods of other objects. In this article I show you how you can create a Dog. Dog is an animal but is also a mammal, for this reason a Dog needs to extend animal and also Mammal classes. Below is the code to create a Dog:]]></summary></entry><entry><title type="html">JSON API error handling with ruby</title><link href="https://www.jacopobeschi.com/rest/ruby/ruby%20on%20rails/2016/03/29/json-api-error-handling-with-ruby.html" rel="alternate" type="text/html" title="JSON API error handling with ruby" /><published>2016-03-29T07:33:00+00:00</published><updated>2016-03-29T07:33:00+00:00</updated><id>https://www.jacopobeschi.com/rest/ruby/ruby%20on%20rails/2016/03/29/json-api-error-handling-with-ruby</id><content type="html" xml:base="https://www.jacopobeschi.com/rest/ruby/ruby%20on%20rails/2016/03/29/json-api-error-handling-with-ruby.html"><![CDATA[<p>Hello folks, after being inactive for a while I am finally back!<br />
This post is about a technique that I found useful for general error handling with REST API and ruby on rails, but the concept works for any programming language/framework.
Most of the time programmers handles api errors without a general pattern, that’s bad because it’s obvious that is more error prone, by using a general pattern you can also do some interestic automatic operations such as error logging and messaging to a monitoring service. 
<!-- more -->
The base of the approach that i’ve choose is handling errors with Exceptions(that’s what they are made for actually). What we do is create a general exception handler that given an exception name and data will return a particular error response as json depending on which kind of exception was thrown. 
The basic idea is to configure the error handler with and exception name associated to a configuration hash.
In order to make things smoother and be as DRY as possible I’ve made a ruby gem and pushed it to rubygems, if you are interested you can <a href="https://github.com/intrip/jsonapi_errors">take a look at the docs here</a></p>]]></content><author><name></name></author><category term="rest" /><category term="ruby" /><category term="ruby on rails" /><summary type="html"><![CDATA[Hello folks, after being inactive for a while I am finally back! This post is about a technique that I found useful for general error handling with REST API and ruby on rails, but the concept works for any programming language/framework. Most of the time programmers handles api errors without a general pattern, that’s bad because it’s obvious that is more error prone, by using a general pattern you can also do some interestic automatic operations such as error logging and messaging to a monitoring service. The base of the approach that i’ve choose is handling errors with Exceptions(that’s what they are made for actually). What we do is create a general exception handler that given an exception name and data will return a particular error response as json depending on which kind of exception was thrown. The basic idea is to configure the error handler with and exception name associated to a configuration hash. In order to make things smoother and be as DRY as possible I’ve made a ruby gem and pushed it to rubygems, if you are interested you can take a look at the docs here]]></summary></entry><entry><title type="html">Solve problems gracefully with dynamic method generation in ruby</title><link href="https://www.jacopobeschi.com/metaprogramming/rspec/ruby/2015/08/20/solve-problems-gracefully-with-dynamic-method-generation-in-ruby.html" rel="alternate" type="text/html" title="Solve problems gracefully with dynamic method generation in ruby" /><published>2015-08-20T19:46:00+00:00</published><updated>2015-08-20T19:46:00+00:00</updated><id>https://www.jacopobeschi.com/metaprogramming/rspec/ruby/2015/08/20/solve-problems-gracefully-with-dynamic-method-generation-in-ruby</id><content type="html" xml:base="https://www.jacopobeschi.com/metaprogramming/rspec/ruby/2015/08/20/solve-problems-gracefully-with-dynamic-method-generation-in-ruby.html"><![CDATA[<p>Days ago i was writing an Rspec macro to gracefully handle authenticated api via a token. At the start i begun creating a couple of methods, each for every Rest verb: 
	module RequestMacros
	  def get_authorized(uri, user)
		get uri, nil, {‘X-Api-Token’ =&gt; user.api_token}
	  end</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  def post_authorized(uri, data, user, headers = {})
	post uri, data, headers.merge({'X-Api-Token' =&gt; user.api_token})
  end &lt;!-- more --&gt;

  def patch_authorized(uri, data, user, headers = {})
	patch uri, data, headers.merge({'X-Api-Token' =&gt; user.api_token})
  end

  def put_authorized(uri, data, user, headers = {})
	put uri, data, headers.merge({'X-Api-Token' =&gt; user.api_token})
  end

  def delete_authorized(uri, user)
	delete uri, nil, {'X-Api-Token' =&gt; user.api_token}
  end
end
</code></pre></div></div>

<p>As you can see from the code above there is some code duplication, in fact the authorized methods get,delete and post,patch,puth shares the same code besides the fact that the method called is different, for example post_authorized calls post etc. In a general OOP approach we could just extract the logic into a shared method that accepts the verb name to be called and then makes a call with that name. But this time i decided to leverage some ruby metaprogramming technique. In the code below we dynamically create in pair the get,delete and post,patch,put methods; in fact the only thing that changes is the method name #{m}. Here is the code:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>module RequestMacros
  %w(get delete).each do |m|
	class_eval &lt;&lt;-eoc
	  def #{m}_authorized(uri, user)
		  #{m} uri, nil, {'X-Api-Token' =&gt; user.api_token}
	  end
	eoc
  end

  %w(post patch put).each do |m|
	class_eval &lt;&lt;-eoc
	  def #{m}_authorized(uri, data, user, headers = {})
	  	#{m} uri, data, headers.merge({'X-Api-Token' =&gt; user.api_token})
	  end
	eoc
  end
end
</code></pre></div></div>

<p>What we just did is with every verb make a method verb_authorized that calls verb, we couldn’t do that without ruby metaprogramming tools! Leveraging metaprogramming allow us to build readable and compact code in a very fascinating way. That’s all for today, happy coding!</p>]]></content><author><name></name></author><category term="metaprogramming" /><category term="rspec" /><category term="ruby" /><summary type="html"><![CDATA[Days ago i was writing an Rspec macro to gracefully handle authenticated api via a token. At the start i begun creating a couple of methods, each for every Rest verb: module RequestMacros def get_authorized(uri, user) get uri, nil, {‘X-Api-Token’ =&gt; user.api_token} end def post_authorized(uri, data, user, headers = {}) post uri, data, headers.merge({'X-Api-Token' =&gt; user.api_token}) end &lt;!-- more --&gt;]]></summary></entry><entry><title type="html">Ruby: Dynamically create callbacks with metaprogramming</title><link href="https://www.jacopobeschi.com/metaprogramming/ruby/ruby%20on%20rails/2015/06/12/ruby-how-to-dynamically-create-callbacks-with-metaprogramming.html" rel="alternate" type="text/html" title="Ruby: Dynamically create callbacks with metaprogramming" /><published>2015-06-12T18:35:00+00:00</published><updated>2015-06-12T18:35:00+00:00</updated><id>https://www.jacopobeschi.com/metaprogramming/ruby/ruby%20on%20rails/2015/06/12/ruby-how-to-dynamically-create-callbacks-with-metaprogramming</id><content type="html" xml:base="https://www.jacopobeschi.com/metaprogramming/ruby/ruby%20on%20rails/2015/06/12/ruby-how-to-dynamically-create-callbacks-with-metaprogramming.html"><![CDATA[<p>Hello guys, in this post I’ll explain you how you can handle callbacks with metaprogramming on ruby on rails. But before going deeper into detail you should ask me the reason of that: why shall you use callbacks instead of using general oop techniques? 
For example in a classic oop design given that you have:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Class X
   def method_x(*args)
 	  #do something
   end
  	end &lt;!-- more --&gt; if you want to do something after calling method x you can easilly override the method in a module like this:

module X
	def method_x(*args)
		super(*args)
		# do something more
	end
end
</code></pre></div></div>

<p>And then include the module X in your class X.
So why should you handle that with metaprogramming? As first in certain situations you cannot override the method using a classical oop approach, for example when you are already leveraging some metaprogramming to dynamically create a method_x inside an included module like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>module Y
	def self.included(base)
		base.instance_eval do
			def method_x(*args)
				# do something
			end
		end
	end
 end
</code></pre></div></div>

<p>In that case the method_x is dynamically created and you cannot override it easilly and use the “super” classical oop, therefore you need to handle that with a callback. Callbacks also allow you to handle that in a more fashioned and readable way. 	
Let me show you how can you do an after_method_x callback:
Firs of all include the Callbacks method i’ve created:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>module Callbacks
  		extend ActiveSupport::Concern

  module ClassMethods
	  def do_after(method)
		guid = SecureRandom.uuid
		define_method("#{guid}") do |*args|
		  yield self, __send__("#{guid}_#{method}", *args), *args
		end
		alias_method "#{guid}_#{method}", method
		alias_method enum, "#{guid}"
	  end
	end
 end
</code></pre></div></div>

<p>When you use the method do_after it creates a new method using guid to ensure uniqueness, that method yields self allowing to pass a custom block, and then calls the original method aliased as #{guid}_#{method}.
To use that in your class you coud do like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Class X
  	include Callbacks
	do_after(:method_x) do |klass, result, *args|
		# do wathever you like here in the block
	end
 end
</code></pre></div></div>

<p>And we have handled a do_after leveraging metaprogramming. I let you imagine the other hooks by yourself.
Have fun and Happy coding!</p>]]></content><author><name></name></author><category term="metaprogramming" /><category term="ruby" /><category term="ruby on rails" /><summary type="html"><![CDATA[Hello guys, in this post I’ll explain you how you can handle callbacks with metaprogramming on ruby on rails. But before going deeper into detail you should ask me the reason of that: why shall you use callbacks instead of using general oop techniques? For example in a classic oop design given that you have:]]></summary></entry><entry><title type="html">Testing for custom Rails validators with Rspec and metaprogramming</title><link href="https://www.jacopobeschi.com/metaprogramming/ruby%20on%20rails/testing/2015/04/25/testing-for-custom-rails-validators-with-spec-and-metaprogramming.html" rel="alternate" type="text/html" title="Testing for custom Rails validators with Rspec and metaprogramming" /><published>2015-04-25T09:45:00+00:00</published><updated>2015-04-25T09:45:00+00:00</updated><id>https://www.jacopobeschi.com/metaprogramming/ruby%20on%20rails/testing/2015/04/25/testing-for-custom-rails-validators-with-spec-and-metaprogramming</id><content type="html" xml:base="https://www.jacopobeschi.com/metaprogramming/ruby%20on%20rails/testing/2015/04/25/testing-for-custom-rails-validators-with-spec-and-metaprogramming.html"><![CDATA[<p>Hello guys, some days ago I’ve made a custom validator for Rails and I wanted to test that it was used correctly in my model (which uses ActiveModel::Model). 
As a brief preface you have to know that to test for the common Rails validators you can use the <a href="https://github.com/thoughtbot/shoulda-matchers">shoulda matchers</a> library. 
<!-- more -->
But in my case what I’ve done is to unit test the validator (I won’t discuss about that) and then I’ve made a custom matcher to verify that the given classes uses the validator correctly. In order to test for the validator presence in the model I’ve leveraged Ruby metaprogramming. Here is the code where the custom validator is used:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Class MyModel 
	include ActiveModel::Model
	
	validates_with MyValidator, attributes: :urr
</code></pre></div></div>

<p>And here is the custom matcher code:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> RSpec::Matchers.define :have_my_validator do |attr_name|
  # Check for all the callback that have MyValidator on the given attribute attr_name
  match do |actual|
    validator = actual._validate_callbacks.select {|callback|
      callback.filter.attributes == [attr_name.to_sym] &amp;&amp;
          callback.filter.class == MyValidator
    }
    expect(validator.size).to be &gt; 0
  end
end
</code></pre></div></div>

<p>What the matcher does is to:</p>

<ol>
  <li>Fetch the list of all the validation used in the model</li>
  <li>Search for a validator fo MyValidator class and that is applied on a given attribute name</li>
  <li>If any is found the test passes otherwise it fails.</li>
</ol>

<p>You can use the validator as following:
	      expect(object).to have_my_validator(:urr)</p>

<p>You can also be more DRY and extract the class name as a parameter and then use it to match any kind of validator.</p>

<p>That’s all for now. Happy coding!</p>]]></content><author><name></name></author><category term="metaprogramming" /><category term="ruby on rails" /><category term="testing" /><summary type="html"><![CDATA[Hello guys, some days ago I’ve made a custom validator for Rails and I wanted to test that it was used correctly in my model (which uses ActiveModel::Model). As a brief preface you have to know that to test for the common Rails validators you can use the shoulda matchers library. But in my case what I’ve done is to unit test the validator (I won’t discuss about that) and then I’ve made a custom matcher to verify that the given classes uses the validator correctly. In order to test for the validator presence in the model I’ve leveraged Ruby metaprogramming. Here is the code where the custom validator is used:]]></summary></entry><entry><title type="html">Devise remote authentication with rails 4.2</title><link href="https://www.jacopobeschi.com/devise/ruby/ruby%20on%20rails/2015/04/08/devise-remote-authentication-with-rails-4-2.html" rel="alternate" type="text/html" title="Devise remote authentication with rails 4.2" /><published>2015-04-08T21:19:00+00:00</published><updated>2015-04-08T21:19:00+00:00</updated><id>https://www.jacopobeschi.com/devise/ruby/ruby%20on%20rails/2015/04/08/devise-remote-authentication-with-rails-4-2</id><content type="html" xml:base="https://www.jacopobeschi.com/devise/ruby/ruby%20on%20rails/2015/04/08/devise-remote-authentication-with-rails-4-2.html"><![CDATA[<p>Hello guys, I’ve been trying to make remote authentication working with devise and i found this useful post: <a href="http://4trabes.com/2012/10/31/remote-authentication-with-devise/">devise remote authentication</a>. The problem is that the post example wasn’t working correctly with new devise versions (3.4.x); 
In this post I’ll explain you the changes that you need to do to make it work with devise 3.4.
<!-- more -->
Note: Before reading the following part read the other article.
The problem are the changes to Devise Authenticatable class regarding the serialization methods. In order to make it work you need to use the following code in your RemoteAuthenticatable Strategy:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>module Devise
  		module Models
		module RemoteAuthenticatable
</code></pre></div></div>

  	        module ClassMethods

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>	   def serialize_from_session(username, password)
		 resource = User.new
		 resource.username = username
		 resource.password = password
		 resource
	   end

	   def serialize_into_session(resource)
		 #IMP you can only pass two params, no more because of this code :
	 	 # devise.rb.466      args = key[-2, 2]
 		 [resource.username, resource.password]
	   end
	 end
  
  	 end
	end
end
</code></pre></div></div>

<p>What happens is that devise passes the result of serialize_into_session to serialize_from_session but it fetches only the last 2 items of the return value: “args = key[-2,2]”.
for this reason you need to pass the needed information in a two item array in order to make this work (if you need more data replace the items with an hash). In this example we use the username to identify in a unique way the user and then we create an user with the given username when we deserialize the item (you can also have a custom method that fetches the model form a temporary memory data or a model saved in the database).<br />
I hope you found this article useful! If you have any question feel free to ask me (will help to increase the quality of the post).
Happy coding and enjoy ruby!</p>]]></content><author><name></name></author><category term="devise" /><category term="ruby" /><category term="ruby on rails" /><summary type="html"><![CDATA[Hello guys, I’ve been trying to make remote authentication working with devise and i found this useful post: devise remote authentication. The problem is that the post example wasn’t working correctly with new devise versions (3.4.x); In this post I’ll explain you the changes that you need to do to make it work with devise 3.4. Note: Before reading the following part read the other article. The problem are the changes to Devise Authenticatable class regarding the serialization methods. In order to make it work you need to use the following code in your RemoteAuthenticatable Strategy:]]></summary></entry></feed>