<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rails &#8211; redpanthers.co</title>
	<atom:link href="/category/rails/feed/" rel="self" type="application/rss+xml" />
	<link>/</link>
	<description>Red Panthers - Experts in Ruby on Rails, System Design and Vue.js</description>
	<lastBuildDate>Sun, 06 Sep 2020 06:59:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.2.7</generator>
	<item>
		<title>Rails 5.2.0</title>
		<link>/rails-5-2-0/</link>
				<pubDate>Mon, 29 Apr 2019 11:28:12 +0000</pubDate>
		<dc:creator><![CDATA[levi]]></dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Rails 5]]></category>

		<guid isPermaLink="false">http://redpanthers.co/?p=16152</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[

<p class="western" align="justify"><span style="font-size: large">Cheers everyone, the new Rails 5.2.0 has released. Let’s have a look at the new features and upgrades in it.</span></p>




<p class="western" align="justify"><span style="font-size: large">It’s been too hard to deal with file uploads in Rails. T</span><span style="font-size: large">here’s been a lot of fine plugins available, but it was overdue that we incorporated something right into the framework. Finally, we have one, in the form of <a href="https://github.com/rails/rails/blob/d3893ec38ec61282c2598b01a298124356d6b35a/activestorage/README.md">Active Storage</a></span><span style="font-size: large">. This release includes Active Storage, a new framework provided by Rails to make it easier to upload and process files. With this new framework, we’ve solved for the modern approach of uploading files straight to the cloud. Out of the box, there’s support for Amazon’s S3, Google’s Cloud Storage, and Microsoft Azure Cloud File Storage. If you’re dealing with images, you can create variants on the fly. If you’re dealing with videos or PDFs, you can create previews on the fly. And regardless of the type, you can analyze uploads for metadata extraction asynchronously. This framework is not only used in production, but it is born for production.</span></p>




<p class="western" align="justify"><span style="font-size: large">There’s a sparkling new <a href="https://github.com/rails/rails/pull/31134">Redis Cache Storage</a> that incorporates general partial, fragment, and other Rails caching jobs into a cohesive unit that anyone can use.</span></p>


<span style="font-size: large">This new Redis Cache Store supports Redis::Distributed, for Memcached-like sharding across Redises. It’s fault tolerant, so will treat failures like misses, rather than kill the request with an exception. It even supports distributed MGETs for that full partial collection caching goodness.</span>


<h3 class="western" align="justify"></h3>




<p class="western" align="justify"><span style="font-size: large">Rails 5.2.0 has Added support for PostgreSQL operator classes to </span><code class="western"><span style="font-size: large">add_index.
</span></code><span style="font-size: large">The operator classes identify database operators to be used by the index for the columns. You can assign the same operator to all columns, or not. It currently only supports PostgreSQL.</span>


<p class="western" align="justify"><span style="font-size: large">Added ability to create PostgreSQL foreign keys without validation. Normally, PostgreSQL verifies that all rows in a table satisfy its foreign keys constraints. With this option, you can create these constraints without the overhead of checking if they are valid.</span></p>




<p class="western" align="justify"><span style="font-size: large">Rails 5.2.0 also has embraced the cherry of HTTP/2 with early hints. This means we can automatically instruct the web server to send required style sheet and JavaScript assets early. This means a faster page delivery.</span></p>




<p class="western" align="justify"><span style="font-size: large">On the topic of performance, Rails now ships with <a href="https://github.com/Shopify/bootsnap">Bootsnap</a> in the default </span><code class="western"><span style="font-size: large">Gemfile</span></code><span style="font-size: large">. This generally reduces application boot times by over 50%.</span></p>




<p class="western" align="justify"><span style="font-size: large"> CSRF and XSS have enhanced that further in Rails 5.2 with the addition of a new DSL that allows you to configure a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy">Content Security Policy</a> for your application. We can configure a global default policy and then override it on a per-resource basis and even use lambdas to inject per-request values into the header such as account subdomains in a multi-tenant application.</span></p>




<p class="western" align="justify"><span style="font-size: large">In Rails 5.2, we’ve rectified the mess by deprecating the two different kinds of secrets and introduced a new shared concept called <a href="https://github.com/rails/rails/pull/30067">Credentials</a>. Credentials, like AWS access keys and other forms of logins and passwords, were the dominant use case for secrets. </span><span style="font-size: large">Credentials are always encrypted. This means they’re safe to check into revision control, as long as you keep the key out of it. This means atomic deploys and there is no need to mess with environment variables.</span></p>




<p class="western" align="justify"><span style="font-size: large">Since Rails 5.1, we’ve also made great strides with <a href="https://github.com/rails/webpacker">Webpacker</a>. So Rails 5.2 is meant to pair beautifully with the new Webpacker 3.0 release. Rails have fully embraced modern JavaScript with a pre-configured build pipeline run by Webpack. We keep strengthening that relationship.</span></p>




<p class="western" align="justify"><span style="font-size: large">Thanks again to everyone who continue to pour their love and support into Ruby on Rails! Happy Coding.</span></p>

]]&gt;		</p>
]]></content:encoded>
										</item>
		<item>
		<title>Configuring a GitLab CI pipeline for Rails, MongoDB, and Rspec</title>
		<link>/configuring-a-gitlab-ci-pipeline-for-rails-mongodb-and-rspec/</link>
				<pubDate>Mon, 29 Apr 2019 11:28:12 +0000</pubDate>
		<dc:creator><![CDATA[tony]]></dc:creator>
				<category><![CDATA[DevOps]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://redpanthers.co/?p=16200</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[<a href="https://about.gitlab.com/">Gitlab</a> has a free private git repository service and an integrated CI service that can be configured to suit our needs. To know more about setting up Gitlab CI, check out our [blog post](link here)


<h3>Including MongoDB in CI build system</h3>


Instead of installing and starting MongoDB manually, we can use the Gitlab mongo service. A Gitlab service is just another Docker image that runs during your job and is linked to the main image. The first step is to include the latest MongoDB image to the build system. Add this to your <code>.gitlab-ci.yml</code>


<pre class="lang:yaml decode:true ">services:
- mongo:latest</pre>




<h3>Add the MONGODB_URI variable</h3>


Add a <code>variables</code> section within <code>.gitlab-ci.yml</code> to set the <code>MONGODB_URI</code> variable.


<pre class="lang:yaml decode:true">variables:
MONGODB_URI: mongodb://mongo:27017/test_db</pre>




<h3>Add config/mongoid.yml ile</h3>


Add a file <code>config/mongoid.yml.gitlab</code> with the following contents


<pre class="lang:yaml decode:true">test:
  clients:
    default:
      uri: &lt;%= ENV['MONGODB_URI'] %&gt;
</pre>




<h3>Override config/mongoid.yml with config/mongoid.yml.gitlab</h3>


We need to override the local test configuration with the above settings specific to CI. Add the following to the <code>before_script</code> section of <code>.gitlab-ci.yml</code>


<pre class="lang:yaml decode:true">before_script:
  - cp config/database.yml.gitlab config/database.yml</pre>


That&#8217;s it fellas, you are all set


<h3>Summary</h3>


The complete <code>.gitlab-ci.yml</code>


<pre class="lang:yaml decode:true">image: starefossen/ruby-node:latest
services:
  - mongo:latest
variables:
  MONGODB_URI: mongodb://mongo:27017/test_db
before_script:
  - RAILS_ENV=test bundle install --jobs $(nproc) "${FLAGS[@]}"
  - cp config/mongoid.yml.gitlab config/mongoid.yml
  - RAILS_ENV=test bundle exec rake db:create db:migrate
test:
  script:
    - bundle exec rspec</pre>


the contents of <code>config/mongoid.yml</code>


<pre class="lang:default decode:true ">development:
  clients:
    default:
      database: dev_db
      hosts:
        - localhost:27017
      options:
        read:
          mode: :primary
        max_pool_size: 10
production:
  clients:
    default:
      uri: &lt;%= ENV['MONGODB_URI'] %&gt;
      pool_size: &lt;%= ENV['DB_POOL_SIZE'] %&gt;
test:
  clients:
    default:
      database: test_db
      hosts:
        - localhost:27017
      options:
        read:
          mode: :primary
        max_pool_size: 1</pre>


and <code>config/mongoid.yml.gitlab</code>


<pre class="lang:yaml decode:true ">test:
  clients:
    default:
      uri: &lt;%= ENV['MONGODB_URI'] %&gt;</pre>


May you have a green build! :-)]]&gt;		</p>
]]></content:encoded>
										</item>
		<item>
		<title>Building a Multitenant application with Apartment gem</title>
		<link>/building-a-multitenant-application-with-apartment-gem/</link>
				<pubDate>Mon, 29 Apr 2019 11:28:12 +0000</pubDate>
		<dc:creator><![CDATA[nimmy]]></dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=4025</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[If you are a Rails developer, then there may be very chance that you build a multitenant app which serves multiple instances with the same set of code that is available. It has an architecture such that a single instance of a software application serves multiple customers. One user does not see other users' activities nor has access to their data. To better understand, consider a blog application. A user can edit his own articles but has no access to other user's articles. In this article, we will implement the multitenant concept in Rails from scratch. Before that, let's look at the differences between single tenancy and multitenancy in order to understand the concept deeply.


<h2>Single tenancy</h2>


Every customer is having their own software instance and DB and it serves for only one customer. Here, the software can be customized to meet the specific customer requirements as it is independent.


<h2>Multi-tenancy</h2>


Multitenancy implements a shared architecture where a single instance of the software application serves multiple customers. We call each customer as a tenant. Multitenancy ensures data isolation for each client. A multitenant app is easier to maintain and is economical.
The core principle in multitenancy architecture approach is often misunderstood with multi-instance architectures. In multitenancy architecture, it is the single instance of the application which is being shared between multiple tenants. Hence, multi-instance architectures aren’t the same as multi-tenant architectures.


<h2>Advantages</h2>




<ul>
 	

<li>Shared infrastructure lead to lower costs by sharing same power resources and software across its clients.</li>


 	

<li>In single-tenant applications, you have to manage different sets for each client while in multitenant applications you have to monitor and provide administration for a single platform only.</li>


 	

<li>Entire system becomes more scalable</li>


 	

<li>Upgrading the software version and installation becomes easier for multitenant applications.</li>


 	

<li>Easier to add new clients.</li>


 	

<li>Configuration can be changed without touching codebase.</li>


 	

<li>Easy maintenance</li>


</ul>




<h2 id="multitenancyonthedatabaselayer">Multi-tenancy on the database layer or model layer</h2>


Multitenancy can be done on the database layer or model layer. Both solutions have pros and cons.
The concept of <strong>multitenancy on database layer</strong> is creating for each user a new database or schema which is the best method to avoid data leaking to another tenant. But some applications have architecture constraints where only one database can exist in the application.
The concept of <strong>multi-tenancy on the model layer</strong> is faster and easier to implement based on ActiveRecord default scopes, but also riskier. In one database, each customer is connected with his own tenanted models by the foreign key. A bug in the application can cause irreversible data leaks from one tenant to another.
The two most popular Ruby Gems which allow for creating multi-tenancy in Rails are:


<ul>
 	

<li>apartment tenancy on database layer: <a href="https://github.com/influitive/apartment">https://github.com/influitive/apartment</a>.</li>


 	

<li>acts<em>as</em>tenant tenancy on model layer: <a href="https://github.com/ErwinM/acts_as_tenant">https://github.com/ErwinM/acts<em>as</em>tenant</a>.</li>


</ul>


It&#8217;s impossible to conclude a universally best solution for multi-tenancy, but Apartment gem seems most reasonable to use when we use Postgres schemas.
In this blog post, we are gonna use Apartment gem to implement multitenancy in Rails application.


<h2>Using Apartment gem</h2>


Apartment gem provides tools to handle multiple tenants in our Rails application. It has a simple installation process and it basically creates tenants and to each tenant, the gem will automatically assign a new isolated schema and the creation of isolated database instances is also possible with Apartment.


<p id="72b6" class="graf graf--h3 graf-after--p">Let&#8217;s create a new Rails app</p>




<pre class="lang:default decode:true">rails new blog-post -d postgresql
</pre>




<pre class="lang:default decode:true">cd blog-post
</pre>




<pre class="lang:default decode:true">bundle exec rake db:create
</pre>




<h3>Adding the Apartment gem to your Gemfile</h3>




<p id="0f9a" class="graf graf--p graf-after--h3">Now open up the <strong class="markup--strong markup--p-strong">Gemfile</strong> in your rails app and add,</p>




<pre name="7b61" id="7b61" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">gem 'apartment'</code></pre>




<p id="0d41" class="graf graf--p graf-after--pre">Now generate the <strong class="markup--strong markup--p-strong">apartment</strong> config file,</p>




<pre name="9d96" id="9d96" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">bundle exec rails g apartment:install</code></pre>




<p id="8812" class="graf graf--p graf-after--pre">This will create a <strong class="markup--strong markup--p-strong">config/initializers/apartment.rb</strong> file as the configuration file for us. There is a bunch of configuration stuff to use.</p>




<h3 id="82fb" class="graf graf--h3 graf-after--p">Create the model</h3>




<p id="884c" class="graf graf--p graf-after--h3">For example usage, we will be creating models author and post.</p>




<pre class="lang:default decode:true">bundle exec rails g model user name
</pre>




<pre class="lang:default decode:true">bundle exec rails g model article content
</pre>


Here users play the role of tenants and articles will be tenanted data. Each user must have a separate schema in Postgres database. We assume that user&#8217;s name is a valid Postgres schema name. We have to add a unique constraint to it.
In the users table migration file,


<pre class="lang:default decode:true">class CreateUsers &lt; ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :name, null: false
    end
    add_index :users, :name, unique: true
  end
end</pre>


Also, add validation in <code>app/models/user.rb</code>:


<pre class="lang:default decode:true">validates :name, presence: true, uniqueness: true</pre>


Then run migration:


<pre class="lang:default decode:true">bundle exec rails db:migrate</pre>


In Apartment gem, each tenant should be created and deleted when the new author is created and removed.
Adding Apartment methods calls in <code>app/models/user.rb</code> :


<pre class="lang:default decode:true">class User &lt; ApplicationRecord
  validates :name, presence: true, uniqueness: true
  after_create do |user|
    Apartment::Tenant.create(user.name)
  end
  after_destroy do |user|
    Apartment::Tenant.drop(user.name)
  end
end</pre>


This will automatically create a <strong class="markup--strong markup--p-strong">tenant</strong> whenever a <strong class="markup--strong markup--p-strong">user </strong>is created by taking the value of <b>name</b> field in the <code>User</code> model (create a Postgres schema for new the user) and remove from the database it when the user is deleted.


<h3>Specify common models</h3>


In any multitenant application, some models will be common for all the tenants and some will be tenant-specific models. In our example, <code>Article</code> model will belong to a tenant and the <code>User</code> model will be excluded from it and remain in the global (public) namespace. So we need to specify it in <code>config/initializers/apartment.rb</code>:


<pre class="lang:default decode:true">--------------------------
Apartment.configure do |config|
# Add any models that you do not want to be multi-tenanted, but remain in the global (public) namespace.
# A typical example would be a Customer or Tenant model that stores each Tenant's information.
config.excluded_models = %w{ User }
--------------------------
</pre>


Now, we have the <code>User</code> model as the common model.


<h3>Specify tenant names</h3>


Apartment gem needs to specify tenant names and assign them accordingly to run migrations for them and create proper tables in Postgresql schemas. In our case, we have to modify only one uncommented option below the <strong class="markup--strong markup--p-strong">excluded models</strong> line that we have added in the previous section in <code>config/initializers/apartment.rb</code> to:


<pre class="lang:default decode:true">config.tenant_names = lambda { User.pluck(:name) }</pre>




<h3>Specify a middleware</h3>


To tell the application to work with <strong class="markup--strong markup--p-strong">subdomains,</strong>  ensure that the following line at the end of the <strong class="markup--strong markup--p-strong">apartment.rb</strong> file is left uncommented.


<pre class="lang:default decode:true">Rails.application.config.middleware.use Apartment::Elevators::Subdomain</pre>




<h2>See it works</h2>


Finally, see how multi-tenancy in the Apartment gem works by creating two users in Rails console.


<pre class="lang:default decode:true">User.create (name: 'Angel')
User.create (name: 'Sam')</pre>


This will create users and also two schemas with articles table for both of them.
By default, we are in the public schema. In order to switch to a different schema we use a special Apartment method:


<pre class="lang:default decode:true">Apartment::Tenant.switch!('Angel')</pre>


This will set current apartment to user named Angel.
Creating some posts for this user in this tenant:


<pre class="lang:default decode:true">Article.create(content: "Angel’s article")
Article.all
=&gt; #&lt;ActiveRecord::Relation [#&lt;Article id: 1, content: "Angel’s article",
created_at: "2018-01-09 09:30:15", updated_at: "2018-01-09 09:30:15"&gt;]&gt;</pre>


Now switch to the second user and show all articles:


<pre class="lang:default decode:true">Apartment::Tenant.switch!('Sam')
Article.all
=&gt; #&lt;ActiveRecord::Relation []&gt;</pre>


We get an empty result, see multitenancy working:)
By the way, showing all users:


<pre class="lang:default decode:true">User.all
=&gt; #&lt;ActiveRecord::Relation [#&lt;User id: 1, name: "Angel"&gt;, #&lt;User id: 2, name: "Sam"&gt;]&gt;</pre>


As the <code>User</code> model is excluded from multi-tenancy it can be seen globally. The public schema has its own articles table, so user&#8217;s posts will not be visible in this schema.
More information can be found on <a href="https://github.com/influitive/apartment">Github gem page</a>, like the built-in ability of Apartment gem to switch tenants per HTTP request.


<h2>References</h2>




<ul>
 	

<li><a href="https://github.com/influitive/apartment">https://github.com/influitive/apartment</a></li>


</ul>

]]&gt;		</p>
]]></content:encoded>
										</item>
		<item>
		<title>Getting started with Faraday gem</title>
		<link>/getting-started-faraday-gem/</link>
				<pubDate>Thu, 16 Nov 2017 17:54:51 +0000</pubDate>
		<dc:creator><![CDATA[nimmy]]></dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=4033</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>Client libraries help in reducing the amount of code for the application developer who is using the API, whether a REST API or any other. By adding a set of code to the application, it provides the basic things an application needs to do in order to interact with the API. This is what a client library does. Also, it may handle user authentication and authorization.</p>
<p>Client libraries are developed by API developer or the community.</p>
<p>There are several HTTP client libraries in Ruby such as:</p>
<ul>
<li>
<h4><a href="https://github.com/jnunemaker/httparty">HTTParty</a></h4>
</li>
<li>
<h4><a href="https://github.com/lostisland/faraday">Faraday</a></h4>
</li>
<li>
<h4>Built-in <a href="http://ruby-doc.org/stdlib-2.2.3/libdoc/net/http/rdoc/Net/HTTP.html">Net::HTTP</a></h4>
</li>
<li>
<h4><a href="https://github.com/rest-client/rest-client">Rest-Client</a></h4>
</li>
<li>
<h4><a href="https://github.com/nahi/httpclient">HTTPClient</a></h4>
</li>
</ul>
<p>Among them, the favorite of mine is Faraday gem. Faraday has adapters for popular libraries like Net::HTTP. It is simple, flexible and supports multiple backends and embraces the concept of Rack middleware when processing the request/response cycle. Also, it&#8217;s possible to customize its behavior with middleware. We will use a connection object to start with Faraday as it&#8217;s more flexible way than a simple <code>get</code>request.</p>
<pre class="lang:default decode:true">conn = Faraday.new
response = conn.get 'http://localhost:3000/tasks'
</pre>
<p>Using this connection object, we make HTTP requests.</p>
<pre class="lang:default decode:true">params = {:title =&gt; 'Faraday gem', :created_by =&gt; 'blog'}
conn.post('http://localhost:3000/tasks',params)
</pre>
<p>This will POST  title = &#8216;Faraday gem&#8217;  and created by = &#8216;blog&#8217; to http://localhost:3000/tasks. All HTTP verb methods can take an optional block that will yield a<code>Faraday::Request</code> object.</p>
<pre class="lang:default decode:true"> conn.post do |req|
   req.url '/tasks'
   req.headers['Content-Type'] = 'application/json'
   req.body = '{"some": "content"}'
 end</pre>
<h2>Authentication</h2>
<p>Basic and Token authentication are handled by <code>Faraday::Request::BasicAuthentication</code> and <code>Faraday::Request::TokenAuthentication</code> respectively. These can be added as middleware manually or through the helper methods.</p>
<pre class="lang:default decode:true">conn.basic_auth('username', 'password')
conn.token_auth('token')</pre>
<h2>Proxies</h2>
<p>To specify an HTTP proxy:</p>
<pre class="lang:default decode:true">Faraday.new(:proxy =&gt; 'http://proxy.example.com:80/')</pre>
<h2>Using a different HTTP Adapter</h2>
<p>Faraday provides an interface between our code and adapter. Sometimes we may want to use features that are not covered in Faraday&#8217;s interface. In such cases, we can have access to features specific to any of the adapters supported by Faraday, by passing a block when specifying the adapter to customize it. For example, you can switch to the HTTPClient adapter as below</p>
<pre class="lang:default decode:true"> conn = Faraday.new do |builder|
   builder.adapter :httpclient do |client| # yields HTTPClient
     client.keep_alive_timeout = 20
   end
 end</pre>
<p>Like this, we can switch to any of the supported adapters. The block parameters will change based on the adapters we are using.</p>
<h2><code>Faraday::Connection</code> object middlewares</h2>
<p>A <code>Faraday::Connection</code> object has a list of middlewares, just like a Rack app. Faraday middlewares are passed as an <code>env</code> hash. It has request and response information.</p>
<pre class="lang:default decode:true">conn = Faraday.new
conn.builder
=&gt; #&lt;Faraday::RackBuilder:0x0000000155d1f0 @handlers=[Faraday::Request::UrlEncoded,
   #Faraday::Adapter::NetHttp]&gt;</pre>
<p><code>Faraday::Builder</code> is similar to <code>Rack::Builder</code>. A new <code>Faraday::Connection</code>object is initialized. It has middlewares <code> Faraday::Request::UrlEncoded</code> in front of an adapter <code>Faraday::Adapter::NetHttp</code>.  Like a Rack application, the adapter at the end of the builder chain is what actually executes the request. Middlewares are grouped into request middlewares, response middlewares, and adapters.</p>
<pre class="lang:default decode:true ">Faraday.new do |builder|
  builder.request :retry
  builder.request :basic_authentication, 'login', 'pass'
  builder.response :logger
  builder.adapter :net_http
end</pre>
<h2>Advanced Middleware Usage</h2>
<p>The order in which middleware is stacked in Faraday is like in Rack. The first middleware on the list wraps all others, while the last middleware is the innermost one, so that’s usually the adapter.</p>
<pre class="lang:default decode:true">conn = Faraday.new(:url =&gt; 'https://redpanthers.co/') do |builder|
  # POST/PUT params encoders:
  builder.request :multipart
  builder.request :url_encoded
  builder.adapter :net_http
end</pre>
<p>Middlewares stack is manipulated by the <code>Faraday::Builder</code> instance. Each <code>Faraday::Connection</code> instance has a <code>Faraday::Builder</code> instance.</p>
<pre class="lang:default decode:true">conn = Faraday.new
conn.builder.swap(1, Faraday::Adapter::HTTPClient)
# replace adapter
conn.builder.insert(0, MyCustomMiddleware)
# add middleware to beginning
conn.builder.delete(MyCustomMiddleware)</pre>
<h2>Writing middleware</h2>
<p>Middlewares are classes that respond to call. When middleware is executing, it&#8217;s passed as an env hash that has request and response information. Middleware wrap the request/response cycle. The general interface for a middleware is:</p>
<pre class="lang:default decode:true">class CustomizedMiddleware
  def call(env)
    # do something with the request
    @app.call(env).on_complete do |env|
    # do something with the response
    end
  end
end</pre>
<p>All processing of the response should be done in the on-complete block. This enables middleware to work in parallel mode when many requests are occurring at the same time. After the on_complete block, env[:response] is filled in. Faraday::Response instance will be available <span class="hljs-keyword">only</span> <span class="hljs-keyword">after</span> `<span class="hljs-string">on_complete`.</span><br />
<a href="https://github.com/lostisland/faraday_middleware">faraday-middleware</a>  is a collection of various Faraday middlewares for Faraday-based API wrappers.<br />
For testing middleware, Faraday::Adapter::Test is an HTTP adapter middleware that lets you to fake responses.</p>
<h2>References</h2>
<ul>
<li><a href="https://github.com/lostisland/faraday">https://github.com/lostisland/faraday</a></li>
</ul>
<p>]]&gt;</p>
]]></content:encoded>
										</item>
		<item>
		<title>Cheat sheet for managing files from Ruby</title>
		<link>/cheat-sheet-for-managing-files-from-ruby/</link>
				<comments>/cheat-sheet-for-managing-files-from-ruby/#comments</comments>
				<pubDate>Fri, 22 Sep 2017 17:34:15 +0000</pubDate>
		<dc:creator><![CDATA[anjana]]></dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=1596</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[In this Cheat sheet, you will learn managing files from Ruby.
Files are used for storing the Data for a Long time Period. And the files can contain any type of information means they can Store the text, any Images or Pictures or any data in any Format. It is associated with class IO File includes.


<h2><span id="Creating_a_New_File_with_Ruby" class="mw-headline">Creating a New File</span></h2>


New files are created in Ruby using the <i>new</i> method of the <i>File</i> class. The <i>new</i> method accepts two arguments, the first being the name of the file to be created and the second being the mode in which the file is to open. Like,
file = File.new(&#8220;filename&#8221;, &#8220;mode&#8221;)
Eg:


<pre class="lang:ruby decode:true ">file = File.new("file.txt", "w")</pre>


Supported modes are:


<table style="height: 206px;" border="1" width="314" cellspacing="0">


<tbody>


<tr>


<td>r</td>




<td>Read only access.</td>


</tr>




<tr>


<td>r+</td>




<td>Read and write access.</td>


</tr>




<tr>


<td>w</td>




<td>Write only access.</td>


</tr>




<tr>


<td>w+</td>




<td>Read and write access.</td>


</tr>




<tr>


<td>a</td>




<td>Write only access.</td>


</tr>




<tr>


<td>a+</td>




<td>Read and write access.</td>


</tr>


</tbody>


</table>




<h2><span id="Opening_Existing_Files" class="mw-headline">Opening Existing Files</span></h2>


You can open the existing files using the open method.
Eg:


<pre class="">file = File.open("temp.txt")</pre>


If the file is already opened, we can close it by using the close method.
Eg:


<pre class="lang:ruby decode:true ">file.close</pre>




<h2>Reading and Writing Files</h2>


Once we&#8217;ve opened an existing file or created a new file we need to be able to read from and write to that file. We can read/write using different methods.


<h3>sysread Method:</h3>


You can use the method <i>sysread</i> to read the contents of a file.
Eg:


<pre class="prettyprint notranslate prettyprinted">file = File.new("input.txt", "r")
if file
   content = file.sysread(10)
   puts content
else
  puts "cannot open the file"
end
</pre>


This statement will output the first 10 characters of the file.


<h3>syswrite Method:</h3>


You can use the method syswrite to write the contents into a file.
Eg:


<pre class="prettyprint notranslate prettyprinted ">file = File.new("input.txt", "r+")
if file
   file.syswrite("Hello")
else
   puts "Unable to open file!"
end
</pre>


It writes &#8216;Hello&#8217; into the file input.txt.


<h3>each_byte Method:</h3>


This method belongs to the class <i>File</i>. The method <i>each_byte</i> is always associated with a block.
Eg:


<pre class="prettyprint notranslate prettyprinted">file = File.new("input.txt", "r+")
if file
   file.syswrite("ABCDEF")
   file.each_byte {|ch| putc ch }
else
   puts "Unable to open file!"
end
</pre>


Characters are passed one by one to the variable ch and then displayed on the screen.


<h3>IO.readlines Method:</h3>


The class <i>File</i> is a subclass of the class IO. This method returns the contents of the file line by line.
Eg:


<pre class="prettyprint notranslate prettyprinted">arr = IO.readlines("input.txt")
puts arr[0]
puts arr[1]
</pre>


Each line of the file <i>input.txt</i> will be an element in the array arr. Therefore, arr[0] will contain the first line, whereas arr[1] will contain the second line of the file.


<h3>IO.foreach Method:</h3>


This method also returns output line by line. The difference between the method <i>foreach</i> and the method <i>readlines</i> is that the method <i>foreach</i> is associated with a block.
Eg:


<pre class="prettyprint notranslate prettyprinted">IO.foreach("input.txt"){|block| puts block}
</pre>


This code will pass the contents of the file <i>test</i> line by line to the variable block, and then the output will be displayed on the screen.


<h2><span id="Renaming_and_Deleting_Files_in_Ruby" class="mw-headline">Renaming and Deleting Files</span></h2>


Files are renamed and deleted in Ruby using the <i>rename</i> and <i>delete</i> methods respectively. For example, we can create a new file, rename it and then delete it:


<pre class="lang:ruby decode:true">File.new("tempfile.txt", "w")
=&gt; #&lt;File:tempfile.txt&gt;
File.rename("tempfile.txt", "newfile.txt")
=&gt; 0
File.delete("newfile.txt")
=&gt; 1</pre>




<h2>References</h2>




<ul>
 	

<li><span style="color: #333399;"><a style="color: #333399;" href="https://www.tutorialspoint.com/ruby/ruby_input_output.html">https://www.tutorialspoint.com/ruby/ruby_input_output.html</a></span></li>


 	

<li><span style="color: #333399;"><a style="color: #333399;" href="http://www.techotopia.com/index.php/Working_with_Files_in_Ruby">http://www.techotopia.com/index.php/Working_with_Files_in_Ruby</a></span></li>


 	

<li><span style="color: #333399;"><a style="color: #333399;" href="https://ruby-doc.org/core-2.2.2/File.html">https://ruby-doc.org/core-2.2.2/File.html</a></span></li>


</ul>

]]&gt;		</p>
]]></content:encoded>
							<wfw:commentRss>/cheat-sheet-for-managing-files-from-ruby/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
							</item>
		<item>
		<title>Refactoring in Rails</title>
		<link>/refactoring-in-rails/</link>
				<comments>/refactoring-in-rails/#comments</comments>
				<pubDate>Wed, 20 Sep 2017 15:31:09 +0000</pubDate>
		<dc:creator><![CDATA[nimmy]]></dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=3038</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[&nbsp;
When the complexity of our Rails application increases, it becomes difficult to test and add new features. As we know, Rails is built on the principle of <a href="https://en.wikipedia.org/wiki/Convention_over_configuration">convention over configuration</a>. Putting too much logic in the controller will eventually violate the <a href="http://www.oodesign.com/single-responsibility-principle.html">single responsibility principle</a> making future changes to the codebase difficult and error-prone. Refactoring the code helps for quality, clarity, and maintainability.


<h2>When should we refactor?</h2>


Tests usually run faster with well-isolated code. Slow running tests indicate the need of more sophisticated design. For example, each class should be concerned about one unique functionality. Also, models and controllers with too many lines of code needed to be refactored to make code DRY and clean. We can use best approaches of Object Oriented Programming to achieve this.
Consider the following example of a controller where the whole logic for creation and deletion is concentrated.


<pre class="lang:ruby decode:true">class WebsitesController &lt; ApplicationController
  def create
    create_website
    find_or_create_user
    fetch_rank
    redirect_to root_url
  end
  def destroy
    .........
  end
.............
  private
  def create_website
    @website = website.first_or_create
    CollectionWebsite.create(collection_id: collection_id, website_id: website.id)
    @website.fetch_meta_description
  end
  def find_or_create_user
    site_urls = user.websites.map(&amp;:url)
    websites_count = user.websites.count
    user.update!(sites: site_urls, site_number: websites_count)
  end
  def fetch_rank
    return if website.alexaranks.any?
    FetchRankJob.perform_later(website)
  end
 end</pre>


&nbsp;


<h2>Moving a big controller&#8217;s action to service objects</h2>


To achieve the new design, keep controllers as thin as possible and always call service objects. Controllers are a good place to have the HTTP routing, parameters parsing, authentication, calling the right service, exception catching, response formatting, and returning the right HTTP status code. A service object&#8217;s job is to hold the code for a particular bit of business logic.
Calling services from controllers result in many classes each of which serves a single purpose. This helps to achieve more isolation between objects. Another important thing is that service objects should be well named to show what an application does. Extracting code from controllers/models to service objects would support single responsibility principle, which leads to better design and better unit tests.
The above example can be rewritten by calling separate services for creating and deleting as shown below. This considerably reduces the number of lines of code in the controller and provides more clarity on the tasks performed.


<pre class="lang:default decode:true">class WebsitesController &lt; ApplicationController
  def create
    Websites::Create.call(website_params, current_user)
    redirect_to root_url
  end
  ..........
  def destroy
    Websites::Delete.call(website_params, current_user)
    redirect_to root_url
  end
  ..........
  private
  def website_params
    params.require(:website).permit(:url, :collection_id)
  end
end</pre>


Now WebsitesController looks cleaner. Service objects are callable from anywhere, like from controllers as well as other service objects, DelayedJob / Rescue / Sidekiq Jobs, Rake tasks, console, etc. In app/services folder, we create services for each controller&#8217;s actions.
Prefer subdirectories for business-logic heavy domains.  For example, the file app/services/websites/create.rb will define Websites::Create while app/services/websites/delete.rb will define Websites::Delete.


<pre class="lang:default decode:true">module Websites
  class Create
    # From the controller, use it like this:
    # Websites::Create.call(params, user)
    def self.call(params, user)
      new(params, user).call
    end
    def initialize(params, user)
      @params = params
      @user = user
      @website = Website.where(url: params[:website][:url])
    end
    def call
      create_website
      find_or_create_user
      fetch_rank
    end
    private
    attr_reader :params, :user, :website
    def create_website
      @website = website.first_or_create
      CollectionWebsite.create(collection_id: collection_id, website_id: website.id)
      @website.fetch_meta_description
    end
    def find_or_create_user
      site_urls = user.websites.map(&amp;:url)
      websites_count = user.websites.count
      user.update!(sites: site_urls, site_number: websites_count)
    end
    def fetch_rank
      return if website.alexaranks.any?
      FetchRankJob.perform_later(website)
    end
  end
end
</pre>


Designing the class for a service object is relatively straightforward, since it needs no special gems and relies on the software design skills only. When the action is complex or needs to interact with an external service, service objects are really beneficial.


<p style="text-align: left;">While refactoring, at each step we have to make sure that none of our tests failed.</p>




<h2>Partials and helpers</h2>


<strong>Partials</strong> and <strong>helpers</strong> are the standard methods to extract reusable functionality. For larger HTML code, partials can be used to split into smaller logic parts. Partials are used for side-menu, header etc.
When developing an application for the first time, I did notice the app/helpers directory but couldn&#8217;t find any use at that time. Generally, helpers are used for chunks of ruby code with minimal HTML or generating simple HTML from parameters. For example,  Once started using it, found it efficient in scenarios where we want to extract some complexity out of view and also if we want to reuse it or want to avoid it one day. This refers mostly to cases like conditionals or calculations.
Consider something like this in the view:


<pre class="lang:default decode:true">&lt;% if @user &amp;&amp; @user.post.present? %&gt;
  &lt;%= @user.post %&gt;
&lt;% end %&gt;</pre>


If put it in a helper,


<pre class="lang:default decode:true">module SiteHelper
  def user_post(user)
    user.post if user &amp;&amp; user.post.present?
  end
end</pre>


And then in the view code, call the helper method and pass it the user as an argument.


<pre class="lang:default decode:true">&lt;%= user_post(@user) %&gt;</pre>


Views are in charge of displaying information only. They are not responsible for deciding what to display.
The concept of object-oriented programming paved the way for design patterns and refactoring patterns such as service objects and also <strong>decorators</strong> and <strong>presenters</strong>. Decorator patterns enable us to attach additional responsibilities to an object dynamically, without affecting other objects of same class. A presenter is a type of<em> </em>subpattern of the decorator pattern. The main difference between them is how they extract logic out of the view. Presenters are very close to the view layer, while decorators are some more broad concept.
Anyway, try to avoid helpers and concerns as much as possible, if you want to make objects easier to test, then Plain Ruby Objects are easier to test than helpers and concerns which are tied to Rails.
The presenter pattern also has the problem of making things harder to test.
Because of this, I prefer to use a mix of POROs (Plain Old Ruby objects) and helpers if can&#8217;t avoid having them. Always keep the minimum amount of code in helpers and move as much logic as possible into POROs. It&#8217;s the same with concerns &#8211; try to avoid them maximum, but it&#8217;s being used in larger code bases.
&nbsp;


<div></div>




<h2>References</h2>




<ul>
 	

<li><a href="https://github.com/adamniedzielski/service-objects-example">https://github.com/adamniedzielski/service-objects-example</a></li>


</ul>


&nbsp;
&nbsp;
]]&gt;		</p>
]]></content:encoded>
							<wfw:commentRss>/refactoring-in-rails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
							</item>
		<item>
		<title>Rails Generators</title>
		<link>/rails-generators/</link>
				<pubDate>Mon, 18 Sep 2017 17:27:20 +0000</pubDate>
		<dc:creator><![CDATA[anjana]]></dc:creator>
				<category><![CDATA[Beginners]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=1441</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[Rails generators are used to create many files for models, controllers, views, unit tests, migrations and more. It will do some of the manual work for us. So it saves time. They can also be used to set up some basic specs for the application test suite.
Running <tt>rails generate(or rails g)</tt> by itself gives a list of available generators:


<pre class="lang:sh decode:true">$ rails generate
Usage: rails generate GENERATOR [args] [options]
...........
Rails:
assets
channel
controller
generator
helper
integration_test
jbuilder
job
mailer
migration
model
resource
responders_controller
scaffold
scaffold_controller
task
.............</pre>


The main generators that rails offers are:


<ul>
 	

<li>controller: The Rails controller coordinates the interaction between the user, the views, and the model.</li>


 	

<li>helper: Code in helpers is included in the corresponding view. We can move big loops, method calls or other logic into a method in the helper.</li>


 	

<li>mailer: It allows for sending and receiving emails from and to your application.</li>


 	

<li>migration: Rails Migration allows you to use Ruby to define changes to your database schema.</li>


 	

<li>model: It is Ruby class that talk to the database, store and validate data, perform the business logic.</li>


 	

<li>scaffold: It refers to the auto-generation of a simple set of a model, views and controller usually for a single table.</li>


</ul>


Following is the list of options, which can be used along with generators:


<p style="padding-left: 30px;">-h, [&#8211;help] # Print generator&#8217;s options and usage
-p, [&#8211;pretend] # Run but do not make any changes
-f, [&#8211;force] # Overwrite files that already exist
-s, [&#8211;skip] # Skip files that already exist
-q, [&#8211;quiet] # Suppress status output</p>




<h2>Generators</h2>


You can create different generators by running <em>rails g</em> in the terminal. Let&#8217;s have a look at each of them.


<ul>
 	

<li>rails generate model ModellName</li>


</ul>




<p style="padding-left: 60px;">It generates the model and the associated database table. For example, we can add a new model to the app called User with fields name and age as,</p>




<p style="padding-left: 60px;">Eg:  rails g model User name: string age: integer</p>




<ul>
 	

<li>rails generate controller ListController show edit</li>


</ul>




<p style="padding-left: 60px;">It generates controller. It is used if you are creating static views or non-CRUD related features. Let&#8217;s create a user controller that will manage the data flow and view for each users.</p>




<p style="padding-left: 60px;">Eg:  rails g controller users</p>




<ul>
 	

<li>rails generate scaffold ModelName ControllerName</li>


</ul>




<p style="padding-left: 60px;">Generates Scaffold. Let&#8217;s create a scaffold User with edit and view actions.</p>




<p style="padding-left: 60px;">Eg:  rails g scaffold User edit view</p>




<ul>
 	

<li>rails generate migration AddNewTable</li>


</ul>




<p style="padding-left: 60px;">Generates Table to migrate. We can create migration for adding a table as</p>




<p style="padding-left: 60px;">Eg:  rails g migration User</p>




<ul>
 	

<li>rails generate plugin PluginName</li>


</ul>




<p style="padding-left: 60px;">Generates Plugin.</p>




<p style="padding-left: 60px;">Eg:  rails g plugin rails_plugin</p>




<ul>
 	

<li>rails generate integration_test TestName</li>


</ul>




<p style="padding-left: 60px;">Generates Integration Test.</p>




<p style="padding-left: 60px;">Eg:  rails generate integration_test User</p>




<ul>
 	

<li>rails generate session_migration</li>


</ul>




<p style="padding-left: 60px;">Generates Session Migration.</p>




<h2 id="creating-generators-with-generators">Creating Generators with Generators</h2>


Generators themselves have a generator:


<pre class="lang:ruby decode:true">$ rails generate generator initializer
 create lib/generators/initializer
 create lib/generators/initializer/initializer_generator.rb
 create lib/generators/initializer/USAGE
 create lib/generators/initializer/templates</pre>


This is the generator just created:


<pre class="lang:default decode:true">class InitializerGenerator &lt; Rails::Generators::NamedBase
  source_root File.expand_path("../templates", __FILE__)
end</pre>




<p class="">First, notice that we are inheriting from <tt>Rails::Generators::NamedBase</tt> instead of <tt>Rails::Generators::Base</tt>. This means that our generator expects at least one argument, which will be the name of the initializer.</p>




<h2>Customizing Rails generators</h2>


We can customize it in, <code>config/application.rb</code>


<pre class="lang:ruby decode:true">config.generators do |g|
  g.orm :active_record
  g.template_engine :erb
  g.test_framework :test_unit, fixture: false
  g.stylesheets false
  g.javascripts false
end</pre>


So by doing the above steps will stop generating stylesheet, JavaScript, and test fixture files. We can avoid generation of unwanted files from doing these steps.
I hope this article help you in some way to know about rails generators.


<h2>References</h2>




<ul>
 	

<li><a href="https://learn.co/lessons/rails-generators-readme">https://learn.co/lessons/rails-generators-readme</a></li>


 	

<li><a href="https://www.tutorialspoint.com/ruby-on-rails/rails-generators.htm">https://www.tutorialspoint.com/ruby-on-rails/rails-generators.htm</a></li>


 	

<li><a href="http://www.agmprojects.com/blog/building-a-rails-generator-and-packing-it-into-a-gem">http://www.agmprojects.com/blog/building-a-rails-generator-and-packing-it-into-a-gem</a></li>


</ul>

]]&gt;		</p>
]]></content:encoded>
										</item>
		<item>
		<title>How we made our rspec test suite to run 2x faster</title>
		<link>/made-rspec-test-suite-run-2x-faster/</link>
				<comments>/made-rspec-test-suite-run-2x-faster/#comments</comments>
				<pubDate>Fri, 01 Sep 2017 09:24:27 +0000</pubDate>
		<dc:creator><![CDATA[tony]]></dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[RSpec]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=3040</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[&nbsp;
"<i>Why on earth is my test suite taking so long to run?</i>&#8221;
If you are a developer, you might have asked this question at least once to yourself. So did we, our rails project&#8217;s test suite was taking a good 1 hour 30 minutes to run and we wanted to improve that time so badly that we eventually did exactly that, reducing nearly 1 and half hours to just minutes, and this is how we did it.


<h2>1. Database independent tests</h2>


DB operations are often time-consuming and most of the time we can do away with saving objects to the database to run our tests.
Use test doubles, stubs and mocks instead of creating the real instance of a class and invoking methods on the created instance.


<div>


<pre class="lang:default decode:true">class Student &lt; ActiveRecord::Base
  .
  .
  def name
    first_name +" "+ last_name
  end
end</pre>


Our test case
</div>




<div>


<div>


<pre class="lang:default decode:true">describe Student do
  let (:student) {create(:student, first_name: 'Red', last_name: 'Panther')}
  it 'should return name' do
    student.name.should == 'Red Panther'
  end
end</pre>


This test can be made faster by replacing
</div>




<div>


<pre class="lang:default decode:true">let(:student) {create(:student, first_name: 'Red', last_name: 'panther')}</pre>


with


<div>


<pre class="lang:default decode:true">let(:student) {build_stubbed(:student, first_name: 'Red', last_name: 'Panther')
</pre>




<h2>2) Use gem group</h2>


</div>


Rails preload your gems before running tests. Using gem groups allow rails to load only the environment specific dependencies.


<div><b>#Gemfile</b></div>




<div>


<pre class="lang:default decode:true">group: production do
  gem 'activemerchent'
end
group :test, : development do
  gem 'capybara'
  gem 'rspec-rails'
  gem 'byebug'
end</pre>




<h2><b>3) Use <code>before(:each)</code> and <code>before(:all)</code> hooks carefully</b></h2>


</div>


Since <code>before(:each)</code> runs for every test, be careful what we include inside <code>before(:each)</code> hook. If the code inside <code>before(:each)</code> is slow every single test in your file is going to be slow.
A workaround would be to refactor the code to have fewer dependencies or move them to a <code>before(:all)</code> block which runs only once.
Let&#8217;s say you have


<div>


<pre class="lang:default decode:true">before(:each) do
  @article = create(:article)
  @author = create(:author)
end</pre>


moving them to a <code>before(:all)</code> block
</div>




<div>


<pre class="lang:default decode:true ">before(:all) do
  @article = create(:article)
  @author = create(:author)
end</pre>


Should save you some time but with some drawbacks of its own, for example, the objects <code>@article</code> and <code>@author</code> are not recreated for each test as they in <code>before(:all)</code> block which means any test case that changes the attributes of these objects might affect the result of other following tests.
</div>




<h2>4. Use <code>build_stubbed</code> Instead of <code>build</code></h2>


FactoryGirl.build is not suitable when we want our instance to behave as though it is persisted. In this scenario instead of creating a real class instance, we can use <code>build_stubbed</code> which makes the instance to behave as it is persisted by assigning an id.


<pre class="lang:default decode:true">FactoryGirl.build_stubbed(:student)</pre>


Also note that when we build instance using ` .build` it calls .create on the associated models, where as .build_stubbed calls nothing but .build_stubbed also on associated models as well.


<h2>5. Running tests parallelly</h2>


<a href="https://github.com/grosser/parallel_tests">parallel_tests</a> is a gem that allows us to run tests across multiple CPU cores. A very important thing to take into account when running tests in parallel is to make sure that the tests are independent of each other. Even though parallel_tests uses one database per thread, if there are any shared state between tests that live outside the DB such as Elastic search or Apache solar those dependencies should be taken into account when writing tests.


<h2>6. Use continuous integration</h2>


As our test suite grew into 3k test cases, it was no longer viable to run the entire suite on our local machines. That&#8217;s when we felt the urgency to switch to a CI. We chose <a href="https://circleci.com/">Circle CI</a> which supports parallel builds. We split out tests into multiple virtual machines that run parallelly and it was a huge win for us in terms of test times. Our developers wrote the code and pushed to the repo and the CI took care of the rest. Few popular CI tools are
1) <a href="https://travis-ci.org/">Trvis CI</a>
2) <a href="https://jenkins.io/">Jenkins</a>
3) <a href="https://circleci.com/">CircleCI</a>
4) <a href="https://codeship.com/">Codeship</a>
Automated tests with continuous integration also enhance code quality.


<h2>7. Database cleaner</h2>


We observed an increase in speed after tweaking our database_cleaner strategies a little bit.
To start with, include gem database_cleaner in gemfile.
Inside a separate file <code>spec/support/database_cleaner.rb</code>,
</div>




<div>


<div id="crayon-597801c40a13b848772980-1" class="crayon-line">


<pre class="lang:default decode:true">RSpec.configure do |config|
 
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end
 
  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end
 
  config.before(:each) do
    DatabaseCleaner.start
  end
 
  config.after(:each) do
    DatabaseCleaner.clean
  end
 
end</pre>




<ul>
 	

<li> This will clear the test database out completely before the entire test suite runs.</li>


 	

<li> Sets the default database cleaning strategy to be transactions, which are very fast.</li>


 	

<li> <code>DatabaseCleaner.start</code> and <code>DatabaseCleaner.clean</code> hook up database_cleaner when each test begins and ends.</li>


</ul>


</div>


</div>


</div>




<h2>References</h2>




<ul>
 	

<li><a href="https://github.com/grosser/parallel_tests">https://github.com/grosser/parallel_tests</a></li>


 	

<li><a href="https://github.com/thoughtbot/factory_girl">https://github.com/thoughtbot/factory_girl</a></li>


 	

<li><a href="https://circleci.com/">https://circleci.com/</a></li>


 	

<li><a href="https://github.com/DatabaseCleaner/database_cleaner">https://github.com/DatabaseCleaner/database_cleaner</a></li>


</ul>




<div></div>

]]&gt;		</p>
]]></content:encoded>
							<wfw:commentRss>/made-rspec-test-suite-run-2x-faster/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
							</item>
		<item>
		<title>Concurrent-Ruby</title>
		<link>/concurrent-ruby/</link>
				<comments>/concurrent-ruby/#comments</comments>
				<pubDate>Thu, 31 Aug 2017 13:14:13 +0000</pubDate>
		<dc:creator><![CDATA[anjana]]></dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=1669</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[<a href="https://redpanthers.co/wp-content/uploads/2017/02/concurrent-ruby-logo-300x300.png"><img class="aligncenter wp-image-1674 size-full" title="Concurrent Ruby" src="https://redpanthers.co/wp-content/uploads/2017/02/concurrent-ruby-logo-300x300.png" alt="Concurrent Ruby" width="300" height="300" /></a>
Concurrent-ruby is a gem that was brought my attention during Anil Wadghule&#8217;s <a href="https://www.youtube.com/watch?v=K8c-gfUcnZA">talk</a> in <a href="http://rubyconfindia.org/">RubyConf India 2017</a>.
Concurrency is the ability of a program to make progress on a task that is spread out over different slices of time. It allows us to run multiple “threads” at the same time. As one thread may be sleeping or waiting on I/O, another thread may take priority and start working, thus making optimal use of available CPU time. When you think of concurrency, think of “threads”.
Modern concurrency tools include agents, futures, promises, thread pools actors, supervisors etc.Concurrent Ruby makes the strongest thread safety guarantees of any Ruby concurrency library. Every abstraction in this library is thread safe. Similarly, all are deadlock free and many are fully lock free.


<h2>Concurrency Abstractions</h2>




<ul>
 	

<li><strong>Async </strong>(<strong>Concurrent::Async</strong>): A mixin module that provides simple asynchronous behavior to a class, turning it into a simple actor.</li>


 	

<li><strong>Future</strong> (<strong>Concurrent::Future</strong>): An asynchronous operation that produces a value. It represents a promise to complete an action at some time in the future.


<ul>
 	

<li><strong>Dataflow</strong>: Built on Futures, Dataflow allows you to create a task that will be scheduled when all of its data dependencies are available.</li>


</ul>


</li>


 	

<li><strong>Promise </strong>(<strong>Concurrent::Promise)</strong>: Similar to Futures, with more features. It represents the eventual value returned from the single completion of an operation.</li>


 	

<li><strong>ScheduledTask</strong> (<strong>Concurrent::ScheduledTask):</strong> Like a Future scheduled for a specific future time.</li>


 	

<li><strong><strong>TimerTask (</strong></strong><strong>Concurrent::TimerTask</strong><strong>)</strong>: A Thread that periodically wakes up to perform work at regular intervals.</li>


</ul>




<h2>Installation</h2>




<div class="highlight highlight-source-shell">


<pre class="">gem install concurrent-ruby</pre>


</div>


or add the following line to Gemfile:


<div class="highlight highlight-source-ruby">


<pre class="">gem 'concurrent-ruby', require: 'concurrent'</pre>


</div>


and run <strong><em>bundle install</em></strong> from your shell.


<h2>Edge Gem Installation</h2>


It is a submodule for unstable, highly experimental features that are likely to change often and which may never become part of the core gem. Also for new, experimental version of abstractions already in the core gem.
The Edge gem must be installed separately from the core gem:


<div class="highlight highlight-source-shell">


<pre class="">gem install concurrent-ruby-edge</pre>


</div>


or add the following line to Gemfile:


<div class="highlight highlight-source-ruby">


<pre class="">gem 'concurrent-ruby-edge', require: 'concurrent-edge'</pre>


</div>


and run <code>bundle install</code> from your shell.


<h2>Usage</h2>


Everything within this gem can be loaded simply by requiring it:


<div class="highlight highlight-source-ruby">


<pre>require 'concurrent'</pre>


</div>


To use the tools in the Edge gem it must be required separately:


<div class="highlight highlight-source-ruby">


<pre class="">require 'concurrent-edge'</pre>


</div>


Eg:


<pre class="lang:ruby decode:true">require 'concurrent-edge'
class Hello
  def greet
    sleep 3
    "Hello, #{Time.now}"
  end
end
all_promises = Concurrent::Promises.zip(
  Concurrent::Promises.future { Hello.new.greet },
  Concurrent::Promises.future { Hello.new.greet }
)
all_promises.then { |*values| puts values.inspect }.value
</pre>


In the above code, it displays greetings. And all these runs concurrently. Here we are using <em>concurrent-edge.</em> It shows the answer as:


<pre class="lang:sh decode:true">Hello, 2016-12-09 08:56:51 +0530
Hello, 2016-12-09 08:56:54 +0530
</pre>


So generally, the gen concurrent-ruby guarantees thread safety and deadlock free. Also, we can manage CPU time using threads in concurrency.


<h2>References</h2>




<ul>
 	

<li><a href="https://github.com/ruby-concurrency/concurrent-ruby">https://github.com/ruby-concurrency/concurrent-ruby</a></li>


 	

<li><a href="https://blog.engineyard.com/2013/ruby-concurrency">https://blog.engineyard.com/2013/ruby-concurrency</a></li>


 	

<li><a href="https://github.com/ruby-concurrency/concurrent-ruby/blob/master/doc/thread_pools.md">https://github.com/ruby-concurrency/concurrent-ruby/blob/master/doc/thread_pools.md</a></li>


</ul>

]]&gt;		</p>
]]></content:encoded>
							<wfw:commentRss>/concurrent-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
							</item>
		<item>
		<title>Custom Loggers</title>
		<link>/custom-loggers/</link>
				<pubDate>Thu, 24 Aug 2017 11:03:57 +0000</pubDate>
		<dc:creator><![CDATA[anjana]]></dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">https://redpanthers.co/?p=1614</guid>
				<description><![CDATA[
				<![CDATA[]]>		]]></description>
								<content:encoded><![CDATA[<p>				<![CDATA[Custom loggers are useful if you wish to have a separate log file for different moving parts of your Rails application. This would make your logging more efficient and readable. (Eg: a file to record all the API request you received). Let's have a look on them!
Note: This could cause an issue of log files growing and consuming the entire space in the hard disk can be managed by configuring Rails application. It is described in our previous article <em><strong><a href="https://redpanthers.co/enable-log-rotation-within-rails-application/">Enable log rotation within the rails application</a>.</strong></em>
Rails make use of ActiveSupport::Logger class to write log information. It is used to output message and has associated levels. You can then give the <a href="https://ruby-doc.org/stdlib-2.1.0/libdoc/logger/rdoc/Logger.html">Logger</a> a level, and only messages at that level or higher will be printed. They are:


<table style="height: 180px;" width="617">


<tbody>


<tr>


<td>UNKNOWN</td>




<td>An unknown message that should always be logged.</td>


</tr>




<tr>


<td>FATAL</td>




<td>An un-handleable error that results in a program crash.</td>


</tr>




<tr>


<td>ERROR</td>




<td>A handleable error condition.</td>


</tr>




<tr>


<td>WARN</td>




<td>A warning.</td>


</tr>




<tr>


<td>INFO</td>




<td>Generic (useful) information about system operation.</td>


</tr>




<tr>


<td>DEBUG</td>




<td>Low-level information for developers.</td>


</tr>


</tbody>


</table>




<h2>CREATE YOUR CUSTOM LOGGER</h2>




<pre class="lang:ruby decode:true"># lib/custom_logger.rb
class CustomLogger &lt; Logger
  def format_message(severity, timestamp, progname, msg)
    "#{msg}\n"
  end
end
logfile = File.open(RAILS_ROOT + '/log/custom.log', 'a') #create log file
logfile.sync = true #automatically flushes data to file
CUSTOM_LOGGER = CustomLogger.new(logfile) #constant accessible anywhere
</pre>


It creates a custom_logger.rb file. Here defines the format for log messages. The arguments are:


<ul>
 	

<li>Severity of the log message</li>


 	

<li>Time instance representing when the message was logged</li>


 	

<li>progname configured or passed to the logger method</li>


 	

<li><em>Object</em> the user passed to the log message.</li>


</ul>




<h2>LOAD CUSTOMLOGGER FROM ENVIRONMENT</h2>


Then load that custom logger in development as:


<pre class="lang:ruby decode:true ">#in any controller, view or model like,
CUSTOM_LOGGER.info("info from custom logger")
CUSTOM_LOGGER.add(Logger::FATAL) { 'Fatal error!' }
CUSTOM_LOGGER.fatal("Some arguments are not given.")
CUSTOM_LOGGER.error ("Argument #{@name} mismatch." )
CUSTOM_LOGGER.debug("This is a " + potentially + " expensive operation")</pre>


I hope this will help you to know about Custom Loggers.


<h2>References</h2>




<ul>
 	

<li><a href="https://ruby-doc.org/stdlib-2.1.0/libdoc/logger/rdoc/Logger.html">https://ruby-doc.org/stdlib-2.1.0/libdoc/logger/rdoc/Logger.html</a></li>


</ul>

]]&gt;		</p>
]]></content:encoded>
										</item>
	</channel>
</rss>
