Tag: ruby-on-rails

# shared model methods (and callbacks, validates, scopes, associations) - instance and class

module Item  
extend ActiveSupport::Concern
  
  # instance associations, scopes, validations, callbacks, methods, private methods  
  included do    
    belongs_to :user    
    has_many :collaborations, as: :record, dependent: :destroy    
    has_many :collaborators, :through => :collaborations, source: :user
    ...
    validates_presence_of :visibility
    ...
    before_destroy do      
      tags.each do |tag|        
        tag.destroy if tag.should_delete?      
      end    
    end
    
    def owner_handle      
      '@' + owner.username unless owner.nil?    
    end    

    private

    def private_method     
      ...   
     end  
  end

  class_methods do
    def self.search(search)
       ...
    end
  end
end

Like JavaScript anonymous undefined functions

With the yield statement

def test
   puts "You are in the method"
   yield
   puts "You are again back to the method"
   yield
end
test {puts "You are in the block"}


def test
   yield 5
   puts "You are in the method test"
   yield 100
end
test {|i| puts "You are in the block #{i}"}

With each on array

array.each do |element|
  puts element
end

Reduce
The above functions/methods take in an array, multiply all the elements together, then return the result. The main idea behind reduce is taking a bunch of things and reducing them down to a single value.

# Ruby
def getProduct(array)
  array.reduce do |accumulator, element|
    accumulator * element
  end
end 



// JavaScript
const getProduct = array => {
  return array.reduce((accumulator, element) => {
    return accumulator * element
  })
}


Filter/Select
The main idea behind filter / select is passing each element to a block; if the element makes the block truthy, the element is added to a new array.

# Ruby
def getOddNums(array)
  array.select { |element| element % 2 != 0 }
end 



// JavaScript
const getOddNums = array => {
  return array.filter((element) => {
    return element % 2 !== 0
  })
}

Map
array = ["11", "21", "5"]

array.map { |str| str.to_i }
# [11, 21, 5]

hash = { bacon: "protein", apple: "fruit" }

hash.map { |k,v| [k, v.to_sym] }.to_h
# {:bacon=>:protein, :apple=>:fruit}