Skip to content

Instantly share code, notes, and snippets.

@mwenger1
Last active July 14, 2017 17:19
Show Gist options
  • Save mwenger1/f991dfa3b94622f0fb184de50710de40 to your computer and use it in GitHub Desktop.
Save mwenger1/f991dfa3b94622f0fb184de50710de40 to your computer and use it in GitHub Desktop.
Commonly used ruby snippets

Polymorphic Relationship

  # db/migrate
  Picture
    t.integer :imageable_id
    t.string  :imageable_type
    OR
    t.references :imageable, polymorphic: true, index: true

  # models  
  class Picture < ApplicationRecord
    belongs_to :imageable, polymorphic: true
  end

  class Employee < ApplicationRecord
    has_many :pictures, as: :imageable
  end

  class Product < ApplicationRecord
    has_many :pictures, as: :imageable
  end

Enum Field

  # db/migrate
  t.integer :affected_side
  
  # model/*.rb
  enum affected_side: { left: 0, right: 1, both: 2, not_applicable: 3 }

  def affected_side_options
    [
      [I18n.t("affected_side.left"), :left],
      [I18n.t("affected_side.right"), :right],
      [I18n.t("affected_side.both"), :both],
      [I18n.t("affected_side.not_applicable"), :not_applicable]
    ]
  end

Capybara Feature Spec

  visit *_path
 
  fill_form_and_submit(:form_name, :action, attrs)
  
  expect(page).to have_content "Content"
  
  click_link "Next Page"

  expect(page).to have_css(".class", text: "Content", match: prefer_exact)

Feature Spec Hooks

  email = ActionMailer::Base.deliveries.last
  page = Capybara::Node::Simple.new(email.to_s)
  
  page.execute_script <<-EOJS
    window.CustomEvent = function(title) {
      var event = document.createEvent("CustomEvent");
      event.initEvent(title, true, true);
      return event;
    };
  EOJS
  
  def last_javascript_event
    event = page.evaluate_script("window.AnalyticsStub.lastEvent()")
    OpenStruct.new(event)
  end

RSpec Instance Double

instance_double(Summary, total: amount)

Inject

  items.inject(0) do |sum, item|
    item.errors.size + sum
  end

Tap

Hash.new.tap do |items|
  items.each_with_index do |item, index|
    items[index.to_s] = item.serialize
  end
end

Accepts Nested Attributes

  # model
  accepts_nested_attributes_for :association_class, allow_destroy: true
  validates_associated :association_class, if: :check_something?

Null Object

class MissingItem
  def activated?
    false
  end
  
  def unique_id
    object_id
  end
end

Working with JSON

  my_json = {
    name: name,
    car: car,
  }.to_json
    
  JSON.parse my_json

ActiveSupport::Concern

def MyMixin
  extend ActiveSupport::Concern
  
  included do
    scope :disabled, -> { where(disabled: true) }
  end
end

Class vs Instance Eval

class String
  def lowercase
    self.downcase
  end
end

String.class_eval do
  def lowercase
    self.downcase
  end
end

---

confusing = "This Is Confusing"
confusing.instance_eval do
  def lowercase
    self.downcase
  end
end   

confusing.lowercase
=> "this is confusing"
"The Smiths on Charlie's Bus".lowercase
(&.) => Safe navigation Operator 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment