<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Juan David Gaviria on Medium]]></title>
        <description><![CDATA[Stories by Juan David Gaviria on Medium]]></description>
        <link>https://medium.com/@juan.gaviria?source=rss-3f37cb11f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vSRbzIv20Ko--vCi</url>
            <title>Stories by Juan David Gaviria on Medium</title>
            <link>https://medium.com/@juan.gaviria?source=rss-3f37cb11f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:35:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juan.gaviria/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to work with Github actions in your rails App + Solr engine.]]></title>
            <link>https://medium.com/kommit-software-developers/how-to-work-with-github-actions-in-your-rails-app-solr-engine-6b218380fa87?source=rss-3f37cb11f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b218380fa87</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[solr]]></category>
            <category><![CDATA[rails-5]]></category>
            <category><![CDATA[ci]]></category>
            <dc:creator><![CDATA[Juan David Gaviria]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 22:01:00 GMT</pubDate>
            <atom:updated>2020-08-03T22:01:00.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to work with GitHub Actions in your rails App + Solr engine.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dosJhluqMe-IVe3hj9JMA.png" /></figure><p>Some weeks ago, I worked on a new CI workflow in my current project, but I had a lot of issues with the Solr service when I tried to integrate all tests in the CI with <a href="https://github.com/features/actions">GitHub Actions</a>. In this post, I want to show you how to make a CI workflow in your Rails app with Solr engine search.</p><p>We will use the following versions:</p><ul><li>Rails 5.2.4</li><li>Ruby 2.5.8</li><li>Postgresql 12.3</li></ul><p>Note: Use rbenv or rvm to manage your Ruby versions, and you can use <a href="https://brew.sh/">Homebrew</a> to install and run Postgresql.</p><p>We’re going to create our project:</p><pre>$ rails _5.2.4_ new rails_solr_app -T -d postgresql<br>$ cd rails_solr_app<br>$ rails db:setup</pre><p>Then we can run our server:</p><pre>$ rails s</pre><p><a href="http://localhost:3000/">http://localhost:3000/</a> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*j9EVZcG85v5CzDvWCKVv6g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd24067a96015a1c8785813c6b88859e/href">https://medium.com/media/bd24067a96015a1c8785813c6b88859e/href</a></iframe><p>We’ll use the Rails scaffold to create a complete CRUD of users:</p><pre>$ rails g scaffold User name:string<br>$ rails db:migrate</pre><p>Add the following line to our routes ⇒ config/routes.rb:</p><pre>root to: &quot;users#index&quot;</pre><p>Refresh the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*jqNj7hg1krP7VXEiG344jg.png" /></figure><p>We need to add some random data, so we can use random_name_generator gem(<a href="https://github.com/folkengine/random_name_generator">https://github.com/folkengine/random_name_generator</a>), then add the following line into the Gemfile:</p><pre>gem &#39;random_name_generator&#39;, &#39;~&gt; 1.2&#39;, &#39;&gt;= 1.2.1&#39;</pre><p>And run:</p><pre>$ bundle install</pre><p>Then we can add some validations on the user’s model:</p><pre>class User &lt; ApplicationRecord<br>  validates :name, presence: true, length: { minimum: 3 }<br>end</pre><p>We can add some users, so we will use the seed generator of rails, we have to edit db/seeds.rb:</p><pre>rng = RandomNameGenerator.new<br>50.times do |i|<br>  name = rng.compose(3)<br>  User.create(name: name)<br>end</pre><p>Now run:</p><pre>$ rails db:seed</pre><p>If you open the rails console, you can see:</p><pre>$ rails c</pre><pre>User.pluck(:name)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5y8Z7x5uU95ncmwLIyfRMQ.png" /></figure><p>The next step is to create a search functionality, so we have to add some gems:</p><pre>gem &#39;jquery-rails&#39;, &#39;~&gt; 4.4&#39;<br>gem &#39;sunspot_rails&#39;, &#39;~&gt; 2.5&#39;</pre><p>In the development and test group:</p><pre>gem &#39;sunspot_solr&#39;, &#39;~&gt; 2.5&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xYXX0hr7SgdQJbdRHsX-Ig.png" /></figure><p>So, you can run:</p><pre>$ bundle install<br>$ rails generate sunspot_rails:install</pre><p>The above command generates a default configuration file(config/sunspot.yml):</p><pre>production:<br>  solr:<br>    hostname: localhost<br>    port: 8983<br>    log_level: WARNING<br>    path: /solr/production<br>    # read_timeout: 2<br>    # open_timeout: 0.5</pre><pre>development:<br>  solr:<br>    hostname: localhost<br>    port: 8982<br>    log_level: INFO<br>    path: /solr/development</pre><pre>test:<br>  solr:<br>    hostname: localhost<br>    port: 8981<br>    log_level: WARNING<br>    path: /solr/test</pre><p>Now, we are going to generate a Solr folder with default configuration files and indexes:</p><pre>$ bundle exec rake sunspot:solr:start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_g1Dyy4wLVRp6eVnOUWxBg.png" /></figure><p>And we will add the following line into .gitignore:</p><pre>/solr/*</pre><p>We will use jquery, so we have to add in app/assets/javascripts/application.js:</p><pre>//= require jquery</pre><p>Add a new route:</p><pre>get &quot;/search&quot; =&gt; &quot;users#search&quot;</pre><p>Modify views/users/index.html.erb:</p><pre>&lt;p id=&quot;notice&quot;&gt;&lt;%= notice %&gt;&lt;/p&gt;</pre><pre>&lt;h1&gt; Search Users&lt;/h1&gt;<br>&lt;%= form_tag(search_path, :method =&gt; &quot;get&quot;, :remote =&gt; true, class: &#39;search-users&#39;) do %&gt;<br>  &lt;%= label_tag(:name, &quot;Search for User name:&quot;) %&gt;<br>  &lt;%= text_field_tag(:name) %&gt;<br>  &lt;%= submit_tag(&quot;Search&quot;) %&gt;<br>&lt;% end %&gt;</pre><pre>&lt;div class=&quot;users-results&quot;&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;h1&gt;All Users&lt;/h1&gt;</pre><pre>&lt;table&gt;<br>  &lt;thead&gt;<br>    &lt;tr&gt;<br>      &lt;th&gt;Name&lt;/th&gt;<br>      &lt;th colspan=&quot;3&quot;&gt;&lt;/th&gt;<br>    &lt;/tr&gt;<br>  &lt;/thead&gt;</pre><pre>&lt;tbody&gt;<br>    &lt;% <a href="http://twitter.com/users">@users</a>.each do |user| %&gt;<br>      &lt;tr&gt;<br>        &lt;td&gt;&lt;%= user.name %&gt;&lt;/td&gt;<br>        &lt;td&gt;&lt;%= link_to &#39;Show&#39;, user %&gt;&lt;/td&gt;<br>        &lt;td&gt;&lt;%= link_to &#39;Edit&#39;, edit_user_path(user) %&gt;&lt;/td&gt;<br>        &lt;td&gt;&lt;%= link_to &#39;Destroy&#39;, user, method: :delete, data: { confirm: &#39;Are you sure?&#39; } %&gt;&lt;/td&gt;<br>      &lt;/tr&gt;<br>    &lt;% end %&gt;<br>  &lt;/tbody&gt;<br>&lt;/table&gt;</pre><pre>&lt;br&gt;</pre><pre>&lt;%= link_to &#39;New User&#39;, new_user_path %&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*9-zFFAyBUN2-FeEVedkb4w.png" /></figure><p>Add a searchable block into User’s model:</p><pre>searchable do<br>  # -- Solr search engine --<br>  text :name<br>end</pre><p>Run:</p><pre>$ bundle exec rake sunspot:solr:reindex</pre><p><strong>Note: Every time that we modify the searchable block, We have to run the above command.</strong></p><p>Now, we will create a service to search users by name, create a new folder models/services and new file models/services/search_users.rb:</p><pre>class Services::SearchUsers<br>  attr_reader   :params</pre><pre>  def initialize(params)<br>    <a href="http://twitter.com/params">@params</a> = params<br>  end</pre><pre>  def search<br>    return [] unless params[:name].present?<br>    results = User.search do<br>      fulltext params[:name] do<br>        fields(:name)<br>      end<br>    end<br>    results.present? ? results.results : []<br>  end<br>end</pre><p>And create a new partial to show all results(views/users/_search_results.json.erb):</p><pre>&lt;% if <a href="http://twitter.com/users">@users</a>.present? %&gt;<br>  &lt;table&gt;<br>    &lt;thead&gt;<br>      &lt;tr&gt;<br>        &lt;th&gt;Search Results&lt;/th&gt;<br>        &lt;th colspan=&quot;3&quot;&gt;&lt;/th&gt;<br>      &lt;/tr&gt;<br>    &lt;/thead&gt;</pre><pre>    &lt;tbody&gt;<br>      &lt;% <a href="http://twitter.com/users">@users</a>.each do |user| %&gt;<br>        &lt;tr&gt;<br>          &lt;td&gt;&lt;%= user.name %&gt;&lt;/td&gt;<br>          &lt;td&gt;&lt;%= link_to &#39;Show&#39;, user %&gt;&lt;/td&gt;<br>        &lt;/tr&gt;<br>      &lt;% end %&gt;<br>    &lt;/tbody&gt;<br>  &lt;/table&gt;<br>&lt;% else %&gt;<br>  &lt;div&gt;<br>    &lt;p&gt;No results&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;% end %&gt;</pre><p>Then, we add search action in the user&#39;s controller:</p><pre>def search<br>  <a href="http://twitter.com/search_user">@search_user</a> = Services::SearchUsers.new(params)<br>  <a href="http://twitter.com/users">@users</a> = <a href="http://twitter.com/search_user">@search_user</a>.search</pre><pre>   respond_to do |format|<br>     format.json do<br>       render json: { data: render_to_string(partial: &#39;users/search_results&#39;, layout: false) }, status: 200<br>      end<br>    end<br>  end</pre><p>Finally, we need to add a JS code to work with JSON response in the search action, so we have to add the following code in assets/javascripts/users.js.coffee (modify extension):</p><pre>$(document).on &quot;ajax:success&quot;, &quot;form.search-users&quot;, (event) -&gt;<br>  [data, status, xhr] = event.detail;<br>  $(&#39;.users-results&#39;).html(data.data);</pre><p>Now, we are going to do some searches:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*TLKYozYWNfMLCwTv1BDW1g.png" /></figure><p>You can see the Solr query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRoWBMPqjG1V6n2Tg8BNYg.png" /></figure><p>But, the default behavior on the Solr schema doesn’t allow us to get similar names, in fact, we have to write the exact name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*SRB2dMTC1zm2Duil7VuS-A.png" /></figure><p>If we want to modify this behavior, we have to do some changes:</p><ol><li>Modify the user’s model:</li></ol><pre>class User &lt; ApplicationRecord<br>  validates :name, presence: true, length: { minimum: 3 }</pre><pre>  searchable do<br>    # -- Solr search engine --<br>    text :name<br>    text :name, :as =&gt; :name_ngram<br>  end<br>end</pre><p>2. Add the following code into solr/configsets/sunspot/conf/schema.xml:</p><pre>&lt;fieldType name=&quot;text_ngram&quot; class=&quot;solr.TextField&quot; omitNorms=&quot;false&quot;&gt;<br>  &lt;analyzer&gt;<br>    &lt;tokenizer class=&quot;solr.WhitespaceTokenizerFactory&quot;/&gt;<br>      &lt;filter class=&quot;solr.LowerCaseFilterFactory&quot; /&gt;<br>      &lt;filter class=&quot;solr.EdgeNGramFilterFactory&quot; minGramSize=&quot;3&quot; maxGramSize=&quot;6&quot;/&gt;<br>  &lt;/analyzer&gt;<br>&lt;/fieldType&gt;</pre><pre>&lt;dynamicField name=&quot;*_ngram&quot; stored=&quot;false&quot; type=&quot;text_ngram&quot; multiValued=&quot;true&quot; indexed=&quot;true&quot;/&gt;</pre><p>3. Run:</p><pre>$ bundle exec rake sunspot:solr:restart<br>$ bundle exec rake sunspot:solr:reindex</pre><p><strong>Note</strong>: <strong>Every time we modify the schema file, we have to restart the Solr service</strong></p><p>4. Now, we can check the correct behavior:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*SuMjaNRzH1Dl3VH_qu6tsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*ZEBmzSASCcdbT-i7kPUqeg.png" /></figure><h3>Tests with rspec</h3><p>Now, we can create some tests for our application, especially the search service, so add in the Gemfile(Test group):</p><pre>gem &#39;rspec-rails&#39;, &#39;~&gt; 4.0&#39;, &#39;&gt;= 4.0.1&#39;<br>gem &#39;database_cleaner-active_record&#39;, &#39;~&gt; 1.8&#39;</pre><p>Run:</p><pre>$ bundle install<br>$ rails generate rspec:install</pre><p>The last command generates boilerplate configuration files:</p><pre>create  .rspec<br>create  spec<br>create  spec/spec_helper.rb<br>create  spec/rails_helper.rb</pre><p>Now, we will create some simple tests to validate the user’s model by creating a new folder spec/models and new file spec/models/user_spec.rb:</p><pre>require &#39;rails_helper&#39;</pre><pre>RSpec.describe &#39;User&#39; do<br>  context &#39;User validations&#39; do</pre><pre>    it &#39;Name can´t be blank&#39; do<br>      expect{ User.create!(name: nil) }.to raise_error(ActiveRecord::RecordInvalid, &quot;Validation failed: Name can&#39;t be blank, Name is too short (minimum is 3 characters)&quot;)<br>    end</pre><pre>    it &#39;Name must be more than 3 character&#39; do<br>      expect{ User.create!(name: &#39;Ju&#39;) }.to raise_error(ActiveRecord::RecordInvalid, &quot;Validation failed: Name is too short (minimum is 3 characters)&quot;)<br>    end</pre><pre>    it &#39;Name is correct&#39; do<br>      expect{ User.create!(name: &#39;Juan&#39;) }.to_not raise_error<br>    end</pre><pre>  end<br>end</pre><p>Then, run all spec files with:</p><pre>$ bundle exec rspec</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AS_NfsGw6TxUXP7GIWlQJA.png" /></figure><p>We have a failure because we didn’t start the solr service into test environment:</p><pre>bundle exec rake sunspot:solr:start RAILS_ENV=test</pre><p><a href="http://localhost:8981/solr/#/">http://localhost:8981/solr/#/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t727MnAIrrhAh1msV6f0ig.png" /></figure><p>And run again all spec files:</p><pre>$ bundle exec rspec</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*IDwrN_6PvPzyxQdoAfMowA.png" /></figure><p>The next step is to create some tests for our search service:</p><p>We need to use database_cleaner gem, by adding in spec/spec_helper.rb:</p><pre>require &#39;database_cleaner/active_record&#39;<br>RSpec.configure do |config|<br>  DatabaseCleaner.strategy = :truncation<br>  .<br>  .<br>  .<br>end</pre><p>Create new folder spec/models/services and new file spec/models/services/search_users_spec.rb:</p><pre>require &#39;spec_helper&#39;</pre><pre>RSpec.describe &quot;Services::SearchUsers&quot; do</pre><pre>before(:all) do<br>    DatabaseCleaner.clean<br>    user_1 = User.create!(name: &#39;Juan David&#39;)<br>    user_2 = User.create!(name: &#39;Juan Antonio&#39;)</pre><pre>User.solr_reindex<br>  end</pre><pre>describe &#39;Search Services&#39; do</pre><pre>it &#39;Should not return any user&#39; do<br>      subject = Services::SearchUsers.new({ name: &quot;Brad&quot; }).search<br>      expect(subject.count).to  eq(0)<br>    end</pre><pre>it &#39;Should be return two user&#39; do<br>      subject = Services::SearchUsers.new({ name: &quot;jua&quot; }).search<br>      expect(subject.count).to  eq(2)<br>    end<br>  end<br>end</pre><p>Run:</p><pre>$ bundle exec rspec</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*nMUJIn5n3YnuAti8GEVrUA.png" /></figure><p>At this point, we have some tests to check into our CI, so we can generate our first commit.</p><h3>Setting up Continuous Integration</h3><p>Continuous Integration (CI) is the process of testing our code every time that we generate changes and these changes are pushed to version control(Github), Github actions is a feature that allows you to define some workflows to run tests.</p><p>We need to create our CI file, so we have some steps:</p><ol><li>Define the name of our workflow =&gt; CI</li><li>Define which events we want to run =&gt; [push, pull_request]</li><li>Define a list of jobs =&gt; test</li><li>Choose operating system =&gt; ubuntu</li><li>Define services =&gt; postgres</li><li>Define steps that we want our workflow to run: Clone our repository(actions/checkout@v1), Set up Ruby, Solr container(5.3.1), Build and run all test</li></ol><p>So, we have to create some folders and one file in the main root of our project =&gt; .github/workflows/ci.yml:</p><pre>name: CI<br>on: [push, pull_request]<br>jobs:<br>  test:<br>    runs-on: ubuntu-latest<br>    services:<br>      db:<br>        image: postgres:11@sha256:85d79cba2d4942dad7c99f84ec389a5b9cc84fb07a3dcd3aff0fb06948cdc03b<br>        ports: [&quot;5432:5432&quot;]<br>        options: &gt;-<br>          --health-cmd pg_isready<br>          --health-interval 10s<br>          --health-timeout 5s<br>          --health-retries 5<br>    steps:<br>      - uses: actions/checkout@v1<br>      - name: Set up Ruby<br>        uses: actions/setup-ruby@v1<br>        with:<br>          ruby-version: &#39;2.5.8&#39;</pre><pre> - name: Create Solr container<br>        run: |<br>          docker run -d --name collabra-solr -p 8981:8983 solr:5.3.1</pre><pre> - name: Build and run tests<br>        env:<br>          DATABASE_URL: postgres://postgres:<a href="http://twitter.com/localhost">@localhost</a>:5432/test<br>          POSTGRES_PASSWORD: postgres<br>          RAILS_ENV: test</pre><pre>        run: |<br>          sudo apt-get -yqq install libpq-dev<br>          gem install bundler:2.1.4<br>          bundle install --jobs 4 --retry 3<br>          curl -o - &#39;<a href="http://localhost:8981/solr/admin/cores?action=CREATE&amp;name=test&amp;configSet=basic_configs&#39;">http://localhost:8981/solr/admin/cores?action=CREATE&amp;name=test&amp;configSet=basic_configs&#39;</a><br>          bundle exec rake db:create<br>          bundle exec rake db:migrate<br>          bundle exec rspec spec</pre><p>We can make a new commit and push our app into a GitHub repository, later go to actions tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*r7bdAPfLWyiqzHPL2HixWg.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F15955381&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fboooooooooooooooom-wow-explode-gif-15955381&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fimages%2Fe0424c778440cf89f54e8922d62594f9%2Ftenor.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/57f9ec6ee8a8f7aced5573ac8b2fc602/href">https://medium.com/media/57f9ec6ee8a8f7aced5573ac8b2fc602/href</a></iframe><p>Ups!!! , we have some errors in our workflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fxfNNchMmq8FRXHiTINrA.png" /></figure><p>The main reason is our custom schema configuration, so we have to work on it, with our Solr image:</p><ul><li>Stop local Solr service:</li></ul><pre>bundle exec rake sunspot:solr:stop RAILS_ENV=test</pre><ul><li>Create an account in Docker(<a href="https://hub.docker.com/signup">https://hub.docker.com/signup</a>) and install docker on your local computer.</li><li>Create an empty folder in your local computer for example my-solr-image.</li><li>Open a new terminal, and go to my-solr-image folder. We are going to copy the solr configuration(5.3.1) in our folder, with the followings commands:</li></ul><pre>$ docker create --rm --name copier solr:5.3.1 <br>$ docker cp copier:/opt/solr/server/solr/configsets/basic_configs custom-config <br>$ docker rm copier</pre><ul><li>Now, we have the default Solr(5.3.1) config:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*doJP-LSGbXQco256scHCsQ.png" /></figure><ul><li>We have to create a new file called Dockerfile(root folder) with the following code(add your information):</li></ul><pre>FROM solr:5.3.1<br>MAINTAINER JUAN GAVIRIA XXX<a href="/service/mailto:juan.gaviria@kommit.co">@XXX.co</a>m</pre><pre>USER root</pre><pre>RUN mkdir -p /opt/solr/server/solr/configsets/myconfig</pre><pre>WORKDIR /opt/solr/server/solr/configsets/myconfig<br>COPY ./custom-config .</pre><pre>WORKDIR /</pre><p>With the above code, we create a new image based on solr:5.3.1 but with our configuration, then run:</p><pre>$ docker build -t my-solr-image .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5cJ-gHX9FuJsKGK1ODVFw.png" /></figure><ul><li>Actually, we have my-solr-image image:</li></ul><pre>$ docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNFsaIGyLNTXlD72aAQNYw.png" /></figure><ul><li>We are going to create a container based on our image, in the port 8981(according to rails_solr_app/config/sunspot.yml):</li></ul><pre>$ docker run -d --name test-image -p 8981:8983 my-solr-image<br>$ docker ps</pre><p>The second command is to check the container status:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6DYHHvqjLtRRRDRiSTccJQ.png" /></figure><p>If we open <a href="http://localhost:8981/solr/#/">http://localhost:8981/solr/#/</a>, we have our container running but without cores:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTsBGZQoUohzHHRpVt0vOA.png" /></figure><ul><li>The next step is to create a core called test, with our custom configuration in the folder myconfig, just open the following link:</li></ul><p><a href="http://localhost:8981/solr/admin/cores?action=CREATE&amp;name=test&amp;configSet=myconfig">http://localhost:8981/solr/admin/cores?action=CREATE&amp;name=test&amp;configSet=myconfig</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*WFHpCphMHoFSwGjynNMbuQ.png" /></figure><p>You can see the custom field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3bzjOUrl3g22rPCCFeLLg.png" /></figure><ul><li>Now, we can run all tests:</li></ul><pre>$ bundle exec rspec</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*FRKSXDMksYm0zBty88Enbg.png" /></figure><ul><li>Later, we have to publish our image(mrjuangaviria ⇒ change for your user in Docker platform):</li></ul><pre>$ docker build -t mrjuangaviria/my-solr-image:1.0 . <br>$ docker push mrjuangaviria/my-solr-image:1.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCngLQy5E-ytQtsCo66Whw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9A_tNb_naMZTmkS6RSa9g.png" /></figure><ul><li>We can use this image into CI Github actions(ci.yml), so change these two lines:</li></ul><pre>docker run -d --name collabra-solr -p 8981:8983 mrjuangaviria/my-solr-image:1.0</pre><pre>curl -o - &#39;<a href="http://localhost:8981/solr/admin/cores?action=CREATE&amp;name=test&amp;configSet=myconfig&#39;">http://localhost:8981/solr/admin/cores?action=CREATE&amp;name=test&amp;configSet=myconfig&#39;</a></pre><ul><li>Finally, we are going to commit and push this change:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*W5eVpaZqgceRhdwInGL41g.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F4108687&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fchirs-farley-shocked-what-huh-omg-gif-4108687&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fimages%2F4afc13daf5603e6e577810f1fb23c0c7%2Fraw&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fed739eb0a7c5c0e2cae82611a1b14c/href">https://medium.com/media/8fed739eb0a7c5c0e2cae82611a1b14c/href</a></iframe><p>You can see the final code <a href="https://github.com/MRJUANGAVIRIA/Rails-Solr_Engine">here</a> !!!!</p><p>I hope this post has been useful, thank you for reading!!!</p><p><strong>References</strong></p><ul><li><a href="https://lucene.apache.org/solr/">https://lucene.apache.org/solr/</a></li><li><a href="https://github.com/sunspot/sunspot">https://github.com/sunspot/sunspot</a></li><li><a href="https://lucene.apache.org/solr/guide/6_6/documents-fields-and-schema-design.html">https://lucene.apache.org/solr/guide/6_6/documents-fields-and-schema-design.html</a></li><li><a href="https://github.com/rspec/rspec-rails">https://github.com/rspec/rspec-rails</a></li><li><a href="https://github.com/DatabaseCleaner/database_cleaner">https://github.com/DatabaseCleaner/database_cleaner</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b218380fa87" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kommit-software-developers/how-to-work-with-github-actions-in-your-rails-app-solr-engine-6b218380fa87">How to work with Github actions in your rails App + Solr engine.</a> was originally published in <a href="https://medium.com/kommit-software-developers">kommit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to protect your rails App from bad clients.]]></title>
            <link>https://medium.com/kommit-software-developers/how-to-protect-your-rails-app-from-bad-clients-a6eda756e1c4?source=rss-3f37cb11f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6eda756e1c4</guid>
            <category><![CDATA[bad-users]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rack-attack]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[scraper]]></category>
            <dc:creator><![CDATA[Juan David Gaviria]]></dc:creator>
            <pubDate>Tue, 23 Jun 2020 15:09:18 GMT</pubDate>
            <atom:updated>2020-07-01T19:07:08.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvDixPPRQ5prsajhSwqsEA.jpeg" /></figure><p>Some months ago, I was working on an implementation to protect my rails app from bad clients or Scrapers, they make a lot of requests in a short period of time, so I started to research some tools(Heroku addon’s) but these tools are expensive, then I found the rack-attack gem(middleware for blocking abusive requests) and decided to develop my implementation with this gem.</p><p>In this tutorial, I want to show you step by step, how to configure and work with rack-attack gem, We will use the following versions:</p><ul><li>Rails 6.0.0</li><li>Ruby 2.6.3</li></ul><p>We’re going to create our project:</p><pre>rails _6.0.0_ new my_rack_attack -T -d postgresql <br>cd my_rack_attac <br>rails db:setup</pre><p>Then we can run our server:</p><pre>rails s</pre><p>Obtain in <a href="http://localhost:3000/">http://localhost:3000/</a> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*1S3iEhn936bUMUGsEPyz5A.png" /></figure><p>We’ll use the Rails scaffold to create a complete CRUD of posts:</p><pre>rails g scaffold Post title  <br>rails db:migrate</pre><p>We add the following line to our routes ⇒ config/routes.rb:</p><pre>root to: &quot;posts#index&quot;</pre><p>If we refresh our browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*FjKuMhQwj_czyvenp7GGsw.png" /></figure><p>We can add some example posts, We will use the seed generator of rails, We have to edit db/seeds.rb:</p><pre>10.times do |i|   <br>  Post.create(title: &quot;Post #{i}&quot;) <br>end</pre><p>Now we run:</p><pre>rails db:seed</pre><p>We will suppose that we want to protect this page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*Rq2Wf0JPfGKzWNYE1vjxSg.png" /></figure><p>Later We need to add rack-attack gem to our Gemfile and figaro gem that allow us to work with environment variables:</p><pre>gem &#39;rack-attack&#39;, &#39;~&gt; 6.2&#39;, &#39;&gt;= 6.2.2&#39; <br>gem &#39;figaro&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*DYHcGnbI97pTK90Vupkm2w.png" /></figure><p>Then we have to run:</p><pre>bundle install</pre><p>We tell our app to use rack-attack as a middleware in config/application.rb:</p><pre>config.middleware.use Rack::Attack</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*CWVFkdJvjhtxdd06tQKugQ.png" /></figure><p>We’ll create our file to manage all environment variables in config/application.yml and We’ll add the first variable:</p><pre>RACK_ATTACK_BLOCK_IPS: 127.0.0.1</pre><p>We test our environment variables in a rails console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*WnLvnQSFRLVNWMzEUtv7yQ.png" /></figure><p>We will manage all protection rules in an initializer file, so we have to create new file config/initializers/rack_attack.rb.</p><p><strong>Case 1</strong></p><p>In this case, we suppose that we know the IP address of the bad user, so we create a blacklist, add the following code in rack_attack.rb:</p><pre>class Rack::Attack<br>  Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new</pre><pre><br>  spammers = ENV[&#39;RACK_ATTACK_BLOCK_IPS&#39;].try(:split, /,\s*/)<br>  if spammers.present?<br>    spammer_regexp = Regexp.union(spammers)</pre><pre>    Rack::Attack.blocklist(&#39;block spam ip&#39;) do |req|<br>      req.ip =~ spammer_regexp<br>    end<br>  end<br>end</pre><p>In the previous code, we get the environment variable RACK_ATTACK_BLOCK_IPS and generate an array of IP’s(blacklist) and use the method blocklist of the Rack::Attack class to block all IP’s in the list and the bad user obtains a 403 response(forbidden), we have modified an initializer so we have to restart the server, If we visit <a href="http://127.0.0.1:3000/">http://127.0.0.1:3000/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*ru9VFVeBccclv1eIqWBuOg.png" /></figure><p><strong>Case 2</strong></p><p>How to block spammers or bad users when trying to make a lot of requests in a short time and we don´t know the IP of the attack origin, we add three more EV in aplication.yml:</p><pre>RACK_ATTACK_RETRY: 2 <br>RACK_ATTACK_FIND_TIME: 10 <br>RACK_ATTACK_BAND_TIME: 60</pre><p>The above variables mean</p><p>RACK_ATTACK_RETRY ⇒ The number of requests that we will allow in a time frame..</p><p>RACK_ATTACK_FIND_TIME ⇒ Period of time(seconds) that rack-attack analyze the number of requests</p><p>RACK_ATTACK_BAND_TIME ⇒ Period of time(seconds) that we will block our app for the attacker.</p><p>In conclusion, for this case, if a user or spammer makes more than two requests in 10 seconds, this user will be blocked for 60 seconds(this configuration will depend on each project), add the following code in initializers/rack-attack.rb:</p><pre>attack_ban_retries  = ENV[&#39;RACK_ATTACK_RETRY&#39;].try(:to_i) || 0<br>attack_ban_findtime = ENV[&#39;RACK_ATTACK_FIND_TIME&#39;].try(:to_i) || 10<br>attack_ban_bandtime = ENV[&#39;RACK_ATTACK_BAND_TIME&#39;].try(:to_i) || 60</pre><pre>if attack_ban_retries &gt; 0<br>  Rack::Attack.blocklist(&#39;allow2ban login scrapers&#39;) do |req|<br>    Rack::Attack::Allow2Ban.filter(req.ip, maxretry: attack_ban_retries, findtime: attack_ban_findtime, bantime: attack_ban_bandtime) do<br>      req.path == &#39;/&#39;<br>     end<br>   end<br>end</pre><pre>ActiveSupport::Notifications.subscribe(/rack_attack/) do |name, start, finish, request_id, payload|</pre><pre>  req = payload[:request]<br>  remote_ip   = req.env[&quot;HTTP_X_FORWARDED_FOR&quot;].presence ||    req.env[&quot;REMOTE_ADDR&quot;].presence<br>  url         = req.env[&quot;REQUEST_URI&quot;].presence<br>  baned_time  = ENV[&#39;RACK_ATTACK_BAND_TIME&#39;].try(:to_i)</pre><pre>  if %i[throttle blocklist].include?(req.env[&#39;rack.attack.match_type&#39;])<br>    Rails.logger.info &quot;[Rack::Attack][PostApp]&quot; &lt;&lt;<br>                  &quot; remote_ip: \&quot;#{remote_ip}\&quot;,&quot; &lt;&lt;<br>                  &quot; banned time: #{baned_time} seconds&quot;<br>   end<br> end</pre><p>In the previous code, we use the filter Allow2Ban(allowing the behavior previous described) and the module ActiveSupport::Notifications to consume notifications(in this case only for an informative log with the IP and the band time, but you could add more logic, for example send an alert email, or save all attack information ), if we restart de server and we make more than 2 requests for 10 seconds we will be banned the app for 60 seconds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzSSaw99VctYqQJCq9Rv8w.png" /></figure><p>In this image, we can check the informative log, later to make more than two requests in 10 seconds, the app returns 403 response, we have to wait for 1 minute to use again the app.</p><p>We could finish with a custom response:</p><pre>Rack::Attack.blocklisted_response = lambda do |env|     <br>  [ 503, {}, [&quot;Server Error\n&quot;]]   <br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Caj88VlkiWOgPsY4doBthg.png" /></figure><p>The final rack-attack.rb file is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*Hv3gvfxw0rEz0MTO1LGYxQ.png" /></figure><p>Rack Attack has a lot of functionalities, It’s up to you to use the best option.</p><p><strong>References</strong></p><ul><li><a href="https://github.com/kickstarter/rack-attack">https://github.com/kickstarter/rack-attack</a></li></ul><p><strong>Credits</strong></p><p><em>Cover image </em><a href="http://www.freepik.com/"><em>Designed by Freepik</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6eda756e1c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kommit-software-developers/how-to-protect-your-rails-app-from-bad-clients-a6eda756e1c4">How to protect your rails App from bad clients.</a> was originally published in <a href="https://medium.com/kommit-software-developers">kommit</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>