Flowdock

Recent notes

RSS feed
May 28, 2019
0 thanks

to_sentence_exclusive

By default, to_sentence combines elements inclusively by using ", and ".

If you want to be exclusive and combine the elements using ", or ", you can either pass in lengthy options to to_sentence or use this handy extension I made to add to_sentence_exclusive to the Array class.

class Array

  # Adds a simple method that overloads `to_sentence` except it uses "or" instead of "and", which is the default.
  # The reason for this is because `to_sentence` is extremely flexible but that results in a lot of code to get
  # the simple result of using "or" instead of "and". This makes it simple.
  #
  def to_sentence_exclusive
    self.to_sentence( two_words_connector: " or ", last_word_connector: ", or " )
  end

end

Just drop this in config/initializers/to_sentence_exclusive.rb, restart your server or console and Bob’s your uncle.

April 19, 2019
0 thanks

Thanks davinjay!

Your note was SUPER helpful so I wanted to leave more than just a “1 thank”.

Cheers!

April 3, 2019
0 thanks

OUTDATED!!!

Man, this stuff is so outdated. Be very careful using anything from here. A lot has changed since Ruby 1.9.

You’ll want to look at the updated docs, like here for Ruby 2.5.1:

ruby-doc.org/core-2.5.1/Time.html#method-i-strftime

They really should just take this site down if they’re not going to keep it updated. Probably does more harm than good now.

January 17, 2019 - (v4.2.7)
0 thanks

This method has been completely removed from Rails 5 onwards

Completely removed from Rails from 5 onwards. See issue: github.com/rails/rails/issues/18336

Just remove from your codebase, or protect with `private` keyword

August 7, 2018
0 thanks

define_method with blocks works differently

As it is already stated that block is evaluated using instance_exec/instance_eval, so let me give you an example.

module Service
  module ClassMethods
    def endpoint_instance_exec(name, &block)
      define_method name do
        instance_exec(&block)
      end
    end

    def endpoint_block_call(name, &block)
      define_method name, &block
    end

    def endpoint_block_improper_call(name, &block)
      define_method name do
        # In this case, we called the block without "instance_eval" that
        # means block was called in the context of class MyService.
        block.call
      end
    end
  end

  def self.included(klass)
    klass.extend ClassMethods
  end

  private

    def hello
      puts 'world'
    end
end

class MyService
  include Service

  endpoint_instance_exec :foo do
    hello
  end

  endpoint_block_call :bar do
    hello
  end

  endpoint_block_improper_call :foobar do
    hello
  end
end

Now, understand how can we execute the code and understand the working of define_method and instance_exec.

MyService.new.foo # => "hello"
MyService.new.bar # => "hello"
MyService.new.foobar # => undefined local variable or method `hello' for MyService:Class
June 4, 2018 - (v4.2.7)
0 thanks

Upload Files Directly To S3 Using Paperclip And Dropzone.js

Upload Files Directly To S3 Using Paperclip And Dropzone.js

by | Dec 22, 2017 | Technical Articles | 0 comments

It’s usually the small time-consuming tasks that frustrate us the most. Such as uploading a file to S3; the requirement is pretty simple but the method chosen to upload the file will decide the efficiency of the task. As uploading files is a feature that most applications require, RailsCarma has compiled a brief tutorial on one of the best methods of getting this task done efficiently: using Paperclip and Dropzone.js.

Paperclip is a popular choice for uploading images and files as it offers great features to handle the attachments;paperclip’ gem is the go-to option. Paperclip allows you to upload multiple images and files, generate thumbnails and even automatically resize the images. It boasts of a large and active community making it the top choice of most developers.
Dropzone.js is an open source library with file drag & drop (with image preview) features.
Amazon S3 is a simple storage device for data storage. We can use it to retrieve images and all type of files.

Why Paperclip?

Paperclip is a popular file uploading tool for the following reasons:

Supports File Caching:
If a form fails to validate, we don’t want the user to pick his file again and re-upload it. Therefore, file caching is necessary from a UX standpoint. And it also conserves the bandwidth.

Processes Images
Paperclip is able to resize and crop images to several different formats thus allowing the developer to choose the library.

Simplifies The Task!
Paperclip gem does not pollute your code and is easy to test!

Allows File Processing
Paperclip allows file processing for EXIF data extraction and thumbnail creation of uploaded PDFs, PSDs, DOCs, XLSXs.

Provides CDN & Storage-Service Support 
This is a big plus as we want to keep the bandwidth to our servers as low as possible and avoid possible data loss due to server failure.

Offers On-The-Fly Processing
Paperclip processes images and files on a per-request basis. This is an innovative feature that enables developers to create custom content that adapts best to different situations.

What Are The Dropzone Asynchronous Events?

addedfile:  When a file is added to the list.
removedfile: Used whenever a file is removed from the list. You can listen to this and delete the file from your server if you want to.
thumbnail: When the thumbnail has been generated. It receives the data URL as second parameter.
error: An error occurred receives the error message as the second parameter. And if the error was due to xmlhttprequest, the xhr object is received as the third parameter.
processing: When a file is processed (since there is a queue, not all files are processed immediately). This event was previously called processingfile.
drop: The user dropped something onto the drop zone.

How Can We Configure Paperclip In Our Application?

has_attached _file: asset
:storage => :s3
:S3_host_name => ENV[“S3_HOST_NAME”]
:S3_region => ENV[“S3_REGION”]
:S3_protocol => ENV[“S3_PROTOCOL”]
:path =>:account_id/:class/:source_id/:attachment/:file_name”,:s3_headers => {‘ContentDisposition’ =>attachment’,content-type’ =>‘application/octet_stream’},
:bucket => ENV[“S3_BUCKET”],
:s3_credentials => Proc.new{|a| a.instance.s3_credentials}
Do_not_validate_attachment_file_type :asset
def s3_credentials
{:access_key_id => ENV[“S3_ACCESS_KEY_ID”], :secret_access_key => ENV[“S3_SECRET_ACCESS_KEY”]}

end 

How Can We Handle Custom Paths In Our Application? Read More from here http://www.railscarma.com/blog/technical-articles/upload-files-directly-s3-using-paperclip-dropzone-js/

June 4, 2018 - (v1_9_3_392)
0 thanks

Urlify Functions & Its Implementation

URLify is a simple gem that refines the conversion of UTF-8 strings to ASCII-safe URI strings and enables it to be used as readable URL-segments. After the gem is installed, you can call the URLify function for any UTF-8 string and it will be automatically converted into an ASCII-safe URI string. URLify also has the additional functionality of being able to remove the subtitles in a given input. ACCENTMAP

‘À’ =>A’,
‘Á’ =>A’,
‘Â’ =>A’,
‘Ã’ =>A’,
‘Ä’ =>A’,
‘Å’ =>AA’,
‘Æ’ =>AE’,
‘Ç’ =>C’,
‘È’ =>E’,
‘É’ =>E’,
‘Ê’ =>E’,
‘Ë’ =>E’,
‘Ì’ =>I’,
‘Í’ =>I’,
‘Î’ =>I’,
‘Ï’ =>I’,
‘Ð’ =>D’,
‘Ł’ =>L’,
‘Ñ’ =>N’,
‘Ò’ =>O’,
‘Ó’ =>O’,
‘Ô’ =>O’,
‘Õ’ =>O’,
‘Ö’ =>O’,
‘Ø’ =>OE’,
‘Ù’ =>U’,
‘Ú’ =>U’,
‘Ü’ =>U’,
‘Û’ =>U’,
‘Ý’ =>Y’,
‘Þ’ =>Th’,
‘ß’ =>ss’,
‘à’ =>a’,
‘á’ =>a’,
‘â’ =>a’,
‘ã’ =>a’,
‘ä’ =>a’,
‘å’ =>aa’,
‘æ’ =>ae’,
‘ç’ =>c’,
‘è’ =>e’,
‘é’ =>e’,
‘ê’ =>e’,
‘ë’ =>e’,
‘ì’ =>i’,
‘í’ =>i’,
‘î’ =>i’,
‘ï’ =>i’,
‘ð’ =>d’,
‘ł’ =>l’,
‘ñ’ =>n’,
‘ń’ =>n’,
‘ò’ =>o’,
‘ó’ =>o’,
‘ô’ =>o’,
‘õ’ =>o’,
‘ō’ =>o’,
‘ö’ =>o’,
‘ø’ =>oe’,
‘ś’ =>s’,
‘ù’ =>u’,
‘ú’ =>u’,
‘û’ =>u’,
‘ū’ =>u’,
‘ü’ =>u’,
‘ý’ =>y’,
‘þ’ =>th’,
‘ÿ’ =>y’,
‘ż’ =>z’,
‘Œ’ =>OE’,
‘œ’ =>oe’,&’ =>and’

Easy Steps To Implement URLify Gem

Go to the Gemfile and add the gem urlify
Run the command bundle install

OR In the terminal, run the command gem install urlify A Demo Of Implementation Of URLify

Here is an example of URLify functionality:

Add gem urlify in your Gemfile
Run bundle install

Read More From Here http://www.railscarma.com/blog/technical-articles/urlify-functions-implementation/

May 3, 2018
0 thanks
April 17, 2018
0 thanks

When using ActionView::Base.new to render templates views

when calling this method to render templates to a string. in order to use any helper methods you need to add them to the view like this

view = ActionView::Base.new(ActionController::Base.view_paths, {})
view.class_eval do  
  # include any needed helpers (for the view)
  include ApplicationHelper
end 

source: http://peden.biz/rendering-a-rails-view-from-a-script/

March 22, 2018
0 thanks

Each attribute has a `reset_<attribute>!` method on it as well.

So if the attribute is name you can call reset_name! on the object to reset the dirty changes.

February 5, 2018
0 thanks

method is working until rails 4

deprecation message and rails line (till v 2.3.8) is not correct. Method exist and working until rails 4.

January 29, 2018 - (<= v3.2.13)
0 thanks

Correction: Getting just the ordinal on Rails 3.

The ordinal method isn’t publicly available in Rails 3 so you can do something like this:

ordinalize(1).last(2) #=> "st"

ordinalize(20).last(2) #=> "th"
December 20, 2017
0 thanks

Effectively identical to Hash#as_json

As of 5.2.0.beta, there is no ActiveRecord::Relation specific implementation. This will result in Object#as_json , which will convert the relation to a hash and call Hash#as_json .

class Object
  def as_json(options = nil) #:nodoc:
    if respond_to?(:to_hash)
      to_hash.as_json(options)
    else
      instance_values.as_json(options)
    end
  end
end
December 20, 2017
0 thanks

Counting with select

If you try to write

Model.select('field_one', 'field_two AS something').count

it will fail (at least for Rails 5.0) with the message PG::SyntaxError: ERROR: syntax error at or near “AS”. In order to fix that issue, you should write

Model.select('field_one', 'field_two AS something').count(:all)
December 9, 2017 - (<= v3.2.13)
0 thanks

Getting just the ordinal on Rails 3.

The ordinal method isn’t publicly available in Rails 3 so you can do something like this:

ordinal(1).last(2) #=> "st"

ordinal(20).last(2) #=> "th"
August 10, 2017 - (v2.2.1 - v4.2.7)
0 thanks

PAGER DUTY & EXCEPTION NOTIFIER PLUGINS FOR RAILS

RAILS EXCEPTION NOTIFIER

The Exception Notifier plugin provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application. It is basically a monitoring tool, which keeps on watching the application and whenever it finds any error, it triggers that error to PagerDuty. To use Exception Notification and PagerDuty in your app, you need to add this gem below:

gem 'exception_notification', '~> 4.1.0'

gem  'pagerduty''

To get the email notifications, you need to include the line below in the development env:

Rails.application.config.middleware.use  ExceptionNotification::Rack,
                 :email => {
                  :email_prefix => "[PREFIX] ",
                  :sender_address => %{"notifier"  <notifier@example.com>},
                  :exception_recipients => %w{exceptions@example.com},
                  :pd => {
                           # simple notifier options
                         }
               }

You can modify sender’s and recipient’s address.

Rails App+PagerDuty

Use the code below in your app with exception notifier to connect with PagerDuty:

require "pagerduty"
module ExceptionNotifier
      Class PdNotifier
          def initialize(options)
            @pagerduty =   Pagerduty.new("0bdcfdacf1b144d7822dfdfa5ed0ab1e")# Service api key
           # do something with the options...
         end
        def call(exception, options={})
           @pagerduty.trigger(exception.message, details:  { backtrace: exception.backtrace })
        end
    end
end

Conclusion

PagerDuty is alert dispatching tool used by operations team/OnCall Engineers to manage the applications and it is popular because of its reliable & rich services(Scheduling,Alerting,Reporting,Call Routing , Feedback & response time).

Create your Free account from app.pagerduty.com/ and integrate with your application to get the flow , how Incident is triggered.

June 28, 2017
0 thanks

How to use Textacular Gem to search data in your Rails Application

We might have heard about a lot many gems which let us implement search functionality in our rails application; for example: searchkick, elasticsearch-rails, ransack and finally, sunspot to work with solr search engine. All these gems have their own advantages. Both searchkick and elasticsearch use redis to search the data as well as need to perform a ‘reindex’ while inserting new data. In one of my recent projects, I happened to use a gem called as Textacular. It’s simple and very easy to use. Textacular Gem:

It is a gem that provides full text search capabilities for PostgreSQL Database. It basically caters to extend the scope of the work performed by activerecord, in a rather friendly manner. It works on heroku as well. This gem works only on PostgreSQL For working with it, let’s first grab the latest textacular gem from rubygems.org/gems/textacular and add it to the gemfile.

gem 'textacular'
    bundle install

Textacular gem provides us with quite a few methods to search the data. So, all our models have the access to use those methods.

basic_search advanced_search fuzzy_search

Usage: Basic_search: It searches based on the input text.

User.basic_search(‘abc’) # Searches on all the model column attributes

User.basic_search(last_name: 'abc', first_name: 'xyz')

Advanced_search: Here, we can use postgres syntaxes like !, & and | (and, or and, not) and then, some others based on the requirement. It converts user’s search DSL into Pg syntax. For this, we need to make sure that the necessary exceptions should be used to handle the syntax errors.

User.advanced_search(last_name: 'text1|text2’) - It  searches with the text1 or text2 on last_name on User  model.

User.advanced_search(last_name: '!text2’) - It searches for the records whose last_name is not text2.

These searches can be chainable as shown below:

User.advanced_search(last_name: 'text1|text2’).basic_search(last_name: 'abc', first_name: 'xyz')

Fuzzy_search: We need to install pg_trgm module to work with fuzzy_search. Run the command below to install this module. It searches for partial appearance of your text in the DB.

rake textacular:create_trigram_migration  
rake db:migrate

Now, we are ready to use fuzzy_search.

User.fuzzy_search('Lorem')

By default, fuzzy search, searches for the records which are 30% of the search text matches with respect to the entire content. We can set this threshold limit by using the command below.

ActiveRecord::Base.connection.execute("SELECT set_limit(0.6);")

So, it expects 60% of search text to match with the original content. We can use OR condition to search on multiple columns. Need to pass a hash with columns with input text as param one and pass second param as a false. It takes AND, if you miss second param or if it True.

User.fuzzy_search({first_name: 'user', last_name: 'test'}, false)

User.fuzzy_search(first_name:user’, last_name: 'test') - It takes AND condition.

By default, the Textacular searches in all text and string columns. We can alter its default behaviour by overriding the searchable_columns method in the model.

def self.searchable_columns
   [:title, :body]
end

We can override self.searchable_language in the model to set proper dictionary settings.

def self.searchable_language 
  'arabic' 
end

Read More : http://www.railscarma.com/blog/technical-articles/how-to-use-textacular-gem-to-search-data-in-your-rails-application/

June 28, 2017
0 thanks

Faker Gem: Fake Data Generation in Ruby

Gems are libraries in Rails that generally enable you to write the application code faster and thereby making a great product in far lesser time. Usually, whenever we start developing any application, there comes a point when we need data which we can use to see how the application will behave while doing some load testing or how it would look when we deploy it to the production. The manual process of creating the data can be daunting. Faker gem serves to take this pain away by generating the fake data just as needed and saving us all the time and effort otherwise wasted in the manual process of data-generation.

It can generate almost any kind of data suitable for our application. For example, it can generate the fake data for fields such as name, email, passwords, phone-numbers, paragraphs, etc. It is therefore, an awesome way of populating the model (which is a database layer in Rails)

Let’s take a look at this gem by creating a sample project. Read More: http://www.railscarma.com/blog/technical-articles/faker-gem-fake-data-generation-ruby/

May 2, 2017
0 thanks

And yet another way to get relative path from absolute globbing

If you execute glob within a block passed to Dir.chdir, you get the paths relative to the directory specified by Dir.chdir… like this…

base_dir = '/path/to/dir'
files = Dir.chdir(base_dir) do
  Dir.glob("**/*.yml")
end
files.first # => 'foo/bar.yml'
March 29, 2017
0 thanks

multiple select has a hidden

It’s unclear if “select_tag” does this but the normal select method also generates a hidden variable if the “multiple” option is set, see http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

March 29, 2017
0 thanks

not submitted even if non-multiple in certain cases.

As a note, just for followers, even if a select is not “multiple” if it is “unselected” (ex: in javascript you can set its value like document.getElementById(‘select_id’).value = ‘a non option’; ). And if that form is submitted, the browser also seems to not send anything about it to the server. So it’s for non-multiples as well, just this case is rare since typically the select will default to its “first value” and then users can only change it another known value, so typically you won’t run into that. This isn’t related to rails but thought I’d mention it.

March 2, 2017
0 thanks

nope

If you pass nil as local file, it doesn’t write the file and only returns the content as string.

March 2, 2017
0 thanks

Converting Hash to Struct in Ruby

With the fact we know about the two, many will perhaps prefer using struct rather than hash. But what we want to focus here is that behind the low performance given by hash, they still can become advantageous. If you can’t use it on its own little way, then convert it into struct so better usability can be achieved.

If you have already defined the struct and you wanted to initiate converting hash to struct, we can help you by using the following methods in a given example below. If you wanted to convert has to a struct in Ruby, let us say for example we have a given of:

h = { :a => 1, :b => 2 }

and want to have a struct such as:

s.a == 1
s.b == 2

To convert, you can do any of these methods: Conversion Method 1:

On this method, the result will appear to be OpenStruct and not specifically as struct:

pry(main)> require 'ostruct'
pry(main)> s = OpenStruct.new(h)
=> #<OpenStruct a=1, b=2>
pry(main)> puts s.a, s.b

Conversion Method 2:

If you have struct defined already and want to start something with a hash, you can follow this:

Person = Struct.new(:first_name, :last_name, :age)

person_hash = { first_name: "Foo", last_name: "Bar", age: 29 }

person =  Person.new(*person_hash.values_at(*Person.members))

=> #<struct Person first_name="Foo", last_name="Bar", age=29>

Conversion Method 3:

Since the hash key order was guaranteed in the Ruby 1.9+, you can follow this:

s = Struct.new(*(k = h.keys)).new(*h.values_at(*k))

The hash to struct conversion example we provided can help, but if you want a more extensive idea, come to professionals for formal assistance. Read More From Here http://www.railscarma.com/blog/technical-articles/guide-converting-hash-struct-ruby/

February 1, 2017 - (v4.1.8 - v4.2.7)
0 thanks

association our data

we can load our data whenever we want.

ActiveRecord::Associations::Preloader.new.preload(@users, :company)
February 1, 2017 - (v4.1.8 - v4.2.7)
0 thanks

Preload our own with out incude

we can preload our data whenever we want.

ActiveRecord::Associations::Preloader.new.preload(@users, :address)
January 24, 2017 - (v4.0.2 - v4.2.7)
0 thanks

How to use belongs_to in Ruby on Rails

Rails 4: Let’s assume we have two models Movie and Actor. Actor has many movies and Movie belongs to Actor. In most of the cases, the developers used to validate the foreign key actor_id is present or not. In this case, it will not validate actor model as to whether the entered actor id exists or not. It is just like attribute validation which always validates that the fields should be non-empty when submitting the form.

Validation with foreign key:
class Movie < ApplicationRecord
belongs_to :actor
validates :actor_id, presence: true
end

class Movie < ApplicationRecord
belongs_to :actor
validates :actor_id, presence: true
end

class Actor < ApplicationRecord
has_many :movies, dependent: :destroy
end

class Actor < ApplicationRecord
has_many :movies, dependent: :destroy
end

The scenario above, validates actor id presence or not like normal attribute presence validator.

Ex: Actor.create(title:abc”).
=> {id: 1, title: 'abc'}
m = Movie.new(title:ok ok”, actor_id: 111)
=> m.valid? => true
=> Actor.find(111)
ActiveRecord::RecordNotFound: Couldn't find Actor with 'id'=111

Ex: Actor.create(title: “abc”).
=> {id: 1, title: 'abc'}
m = Movie.new(title: “ok ok”, actor_id: 111)
=> m.valid? => true
=> Actor.find(111)
ActiveRecord::RecordNotFound: Couldn't find Actor with  'id'=111

We can still save the movie record without valid actor.

With associations

class Movie < ApplicationRecord
belongs_to :actor
validates :actor, presence: true
end

class Movie < ApplicationRecord
belongs_to :actor
validates :actor, presence: true
end

(or)

class Movie < ApplicationRecord
belongs_to :actor, required: true
end

class Movie < ApplicationRecord
belongs_to :actor, required: true
end

class Actor < ApplicationRecord
has_many :movies, dependent: :destroy
end

class Actor < ApplicationRecord
has_many :movies, dependent: :destroy
end

Ex: Actor.create(title:abc”).
==> {id: 1, title: 'abc'}
m = Movie.new(title:ok ok”, actor_id: 111)
==> m.valid? => false
==> m.errors.full_messages, ['Actor can't be blank']

Ex: Actor.create(title:abc”).
==> {id: 1, title: 'abc'}
m = Movie.new(title:ok ok”, actor_id: 111)
==> m.valid? => false
==> m.errors.full_messages, ['Actor can't be blank']

In this case, it will always validate whether the entered actor exists or not. In case of an invalid actor it throws error to you. This is the best practise to make your associations. It always checks for the associated object exists or not.

Rails5 From rails5 these validations were added by default. It validates association object should be present when you define belongs_to associations.

Release notes http://guides.rubyonrails.org/5_0_release_notes.html(belongs_to will now trigger a validation error by default if the association is not present.)

We can opt out of this feature completely from the application by setting config opton in initializer file.

config/initializers/new_framework_defaults.rb

config/initializers/new_framework_defaults.rb

Rails.application.config.active_record.belongs_to_required_by_default = false Rails.application.config.active_record.belongs_to_required_by_default = false

This initializer file is present in rails5 application only. Need to add this initializer file manually when you migrate from older version of your rails application and make necessary changes.

class Post < ApplicationRecord
has_many :comments, dependent: :destroy	
end

class Post < ApplicationRecord
has_many :comments, dependent: :destroy	
end

class Comment < ApplicationRecord
belongs_to :post
end

class Comment < ApplicationRecord
belongs_to :post
end

c = Comment.create(title:awesome post”)
c.errors.full_messages.to_sentence
=>Post must exist”

c = Comment.create(title:awesome post”)
c.errors.full_messages.to_sentence
=>Post must exist”

We can not create any comment record without an associated record.

We can opt out this default behaviour by setting

belongs_to :post, optional: true
belongs_to :post, optional: true
c = Comment.create(title:awesome post”)
c = Comment.create(title:awesome post”)
=> <Comment id: 1, title:awesome post”, post_id: nil>

http://www.railscarma.com/blog/technical-articles/use-belongs_to-ruby-rails/

January 16, 2017
0 thanks

Sort Integers

ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin16]

Sort From Greatest to Smallest

>> [1, 2, 3, 4].sort { |a, z| z <=> a }
=> [4, 3, 2, 1]
January 5, 2017
0 thanks

Clarifying the confusing example

since exit is a keyword in Ruby, the example may be confusing. The following example might be less so:

module Foo
  begin
    # this raises an error b/c baz is not defined here
    alias_method :other_baz, :baz
  rescue NameError =>e
    puts e
  end

  def baz
    puts "first baz called"
  end

  # now that baz method is defined, we can define an alias
  alias_method :other_baz, :baz

  # we can now overwrite baz.
  # If we want the original baz, use the alias we just defined
  def baz
    puts "second baz called"
  end

  def qux
    puts "qux called"
  end
  alias_method :bar, :qux

end

include Foo

# calls the second baz method, b/c it overwrites the first
baz #=> "second baz called"
# calls the first baz method, due to the alias_method making a copy
other_baz #=> "first baz called"
bar #=> "qux called"
qux #=> "qux called"

The resulting output is:

undefined method `baz' for module `Foo'
second baz called
first baz called
qux called
qux called
December 30, 2016
0 thanks

Used within collection_check_boxes

Note the checked: option.

%table
  = collection_check_boxes(:ahj_types, :ids, AhjType.order(:TypeName), :AHJTypeID, :TypeName) do |b|
    %tr
      %td{style: 'padding: 0 1em;'}
        = b.label(class: "check_box")
      %td{style: 'padding: 0 1em;'}
        = b.check_box(class: "check_box", checked: (params[:ahj_types][:ids].member?(b.value.to_s)))
December 15, 2016
0 thanks

Rails caching with dalli gem

Dalli is a high performance pure Ruby client for accessing memcached servers. It works with memcached 1.4+ only, as it uses the newer binary protocol.

Memcache Memcached is a quick in-memory protest reserving framework that can make Rails run much quicker with not very many changes. Memcached is an in-memory key-value store for little pieces of discretionary information (strings, objects) from consequences of database calls, API calls, or page rendering.

Run the command below to install memcached On Ubuntu

sudo apt-get install memcached

On Mac

brew install memcached

Please refer the URL below to know more about installing memcahed

https://github.com/petergoldstein/dalli#installation-and-usage

Install dalli gem
gem 'dalli'

Add the gem above to your gemfile and run bundle install.

Configuration Here, we have to configure our rails app to serve caching mechanisam. Add below line to the production.rb(config/environments/production.rb)

config.cache_store = :dalli_store

Dalli::Client accepts the following options. All times are in seconds.

expires_in: Global default for key TTL. Default is 0, which means no expiry. namespace: By default, it is nil. It’s prepend to each key if you specify namespace. failover: Default is true. Boolean, if true, Dalli will failover to another working server if the main server for a key is down. threadsafe: Boolean. If true, Dalli ensures that only one thread is using a socket at a specified given time. Default is true. serializer: The serializer to use for objects being stored (ex. JSON). Default is Marshal. compress: Boolean, if true Dalli will gzip-compress values larger than 1K. Default is false. compression_min_size: Minimum value byte size for which to attempt compression. Default is 1K. compression_max_size: Maximum value byte size for which to attempt compression. Default is unlimited. Please check more configations at

https://github.com/petergoldstein/dalli#configuration

After this, we have to tell ActionController to perform caching. Add the line below to the same file and restart Rails server if you are already running it.

config.action_controller.perform_caching = true

Please add the code below to your index method

@posts = Rails.cache.fetch('posts', expires_in:  5.minutes){
Post.all
}

Here, Rails.catche.fetch reads the data from ‘posts’ key. If the specified key has any data, it will return data otherwise it will write to that key and it will be available for successive calls within the expiry time.

Rails provides helpers such as Rails.cache.read to read the cache, Rails.cache.write to write in the cache and Rails.cache.fetch to return the results if present in the cache or else, write in the cache to return the results.

You can read more about Rails cache at

http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html

Rails.cache.clear()Flushing all the keys from  memcached.
Rails.cache.delete(‘posts’)If you wish to flush any  specific key from memcached server.

http://www.railscarma.com/blog/technical-articles/rails-caching-dalli-gem/