Flowdock

Recent notes

RSS feed
November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4 - 1.2.0)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4 - 1.1.12)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4 - 1.1.12)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

November 16, 2020 - (1.1.4)
0 thanks

Mr.

555

May 5, 2020
0 thanks

Make your custom enumerable "flattenable"

Just alias to_a to to_ary

class A
  include Enumerable

  def each
    yield "a"
    yield "b"
  end
end

[A.new, A.new].flatten => [#<A:0x00007fbddf1b5d88>, #<A:0x00007fbddf1b5d60>]

class A
  def to_ary
    to_a
  end
end

[A.new, A.new].flatten => ["a", "b", "a", "b"]
April 2, 2020 - (>= v4.2.1)
0 thanks

Works even on nested structures

@EdvardM added a note years ago saying this does not symbolize the keys of deeply nested hashes, which may have been the case for whatever version of ruby was available at the time, but in 4+, it definitely does work as described:

hash = {"a" => :a, "b" => {z: [[{"c" => 3}, {"c" => 4}], []]}}
hash.deep_symbolize_keys
=> {:a=>:a, :b=>{:z=>[[{:c=>3}, {:c=>4}], []]}}
August 26, 2019
0 thanks

expect_any_instance_of(ActiveRecord::Relation).to receive(:create_with) and others do not work

If you’re doing

expect_any_instance_of(ActiveRecord::Relation).to receive(:create_with) 

and it does not work, try:

expect_any_instance_of(ActiveRecord::Associations::CollectionProxy).to receive(:create_with) { |proxy, attributes|
  expect(proxy.klass).to eq(RecordClass)
  expect(attributes[:....]).to eq(...)
  double('find_or_create_by!' => Proc.new {})
}

or when testing “find_or_create_by”

expect_any_instance_of(ActiveRecord::Associations::CollectionProxy).to receive(:find_or_create_by) { |proxy, attributes|
  expect(proxy.klass).to eq(RecordClass)
  expect(attributes[:....]).to eq(...)
}
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.