[et_pb_section admin_label=”section”] [et_pb_row admin_label=”row”] [et_pb_column type=”4_4″][et_pb_text admin_label=”Text”]


Basic ruby program

#!/usr/bin/ruby
puts "This is main Ruby Program"

validations

validations validates :name, presence: true validates :name, :login, :email, presence: true validates :terms_of_service, acceptance: { message: 'must be abided' } 

validates :subdomain, exclusion: { in: %w(www us ca jp), message: "%{value} is reserved." } 

validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/, message: "only allows letters" } 

validates :name, length: { minimum: 2 } validates :bio, length: { maximum: 500 } 

validates :password, length: { in: 6..20 } 

validates :registration_number, length: { is: 6 } 

validates :bio, length: { maximum: 1000, too_long: "%{count} characters is the maximum allowed" } 

validates :points, numericality: true validates :games_played, numericality: { only_integer: true } 

validates :boolean_field_name, inclusion: { in: [true, false] } 

validates :boolean_field_name, exclusion: { in: [nil] } 

validates :name, uniqueness: { scope: :year, message: "should happen once per year" } 

validates :name, uniqueness: { case_sensitive: false } 

validates :title, length: { is: 5 }, allow_blank: true 

validates :age, numericality: { message: "%{value} seems wrong" }
 
validates :name, presence: { message: "must be given please" }
 
validates :email, uniqueness: true, on: :create 

validates :age, numericality: true, on: :update 

class Order < ApplicationRecord 
  validates :card_number, presence: true, if: :paid_with_card? 
  def paid_with_card? 
    payment_type == "card" 
  end 
end 

Associations

  • belongs_to
  • has_one
  • has_many
  • has_many :through
  • has_one :through
  • has_and_belongs_to_many

has_many :through Association

[code language=”ruby”]
class teacher &lt; ActiveRecord::Base has_many :departments has_many :students, :through =&gt; :departments
end

class Department &amp;lt; ActiveRecord::Base
belongs_to :physician
belongs_to :student
end

class Student &lt; ActiveRecord::Base has_many :departments has_many :teachers, :through =&gt; :departments
end
[/code]

has_and_belongs_to_many

[code language=”ruby”]
class Teacher &lt; ActiveRecord::Base
has_and_belongs_to_many :students
end

class Student &amp;lt; ActiveRecord::Base
has_and_belongs_to_many :Teacher
end
[/code]

Polimorphic association

[code language=”ruby”]
class Picture &lt; ActiveRecord::Base
belongs_to :imageable, :polymorphic =&gt; true
end
class Teacher &lt; ActiveRecord::Base
has_many :pictures, :as =&gt; :imageable
end
class Student &lt; ActiveRecord::Base
has_many :pictures, :as =&gt; :imageable
end
[/code]


Callbacks

sdsds

Creating an Object
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit/after_rollback
Updating an Object
before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
after_commit/after_rollback
Destroying an Object
before_destroy
around_destroy
after_destroy
after_commit/after_rollback


define a meta programming method

[code language=”ruby”]
class Developer

["frontend", "backend"].each do |method|
define_method "coding_#{method}" do
p "writing " + method.to_s
end
end

end

developer = Developer.new

developer.coding_frontend
# "writing frontend"

developer.coding_backend
# "writing backend"
[/code]


Block & Proc & Lambda

Block:

  • Is in between the curly braces and in between do and end.
  • No issue with number of arguments.
  • Blocks are basically a proc without a name

def print_once
yield
end
print_once { puts “Block is being run” }

Proc:

  • Similar behaviour as Block.
  • Can be stored in a variable and move around.
  • No issue with number of arguments.
  • Return within the proc would exit the method from where it is called.
1 2 3 4 proc = Proc.new { |x| puts x }
proc.call(2)

Lambda

  • Same as Proc, but closer to a method.
  • Strict regarding the arguments it gets and it needs.
  • Return within a lambda would exit it from the lambda and the method would continue executing.
  • lam = lambda { |x| puts x } # creates a lambda that takes 1 argument lam.call(2)

Summary Differences

  1. Procs are objects, blocks are not
  2. At most one block can appear in an argument list
  3. Lambdas check the number of arguments, while procs do not
  4. Lambdas and procs treat the ‘return’ keyword differently

Better way for implementing API

class Api::ApiController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
  before_action :authenticate_api_keys
  before_action :authenticate_device!, except: [:login]
  before_action :set_locale

  private
  # authenticating the api keys
  def authenticate_api_keys
    api_key = request.headers['Api-Key']
    api_secret = request.headers['Api-Secret']
    if ENV['API_KEY'] == api_key && ENV['API_SECRET'] == api_secret
      true
    else
      raise_unauthorized and return
    end
  end
  # authenticating device with auth token
  def authenticate_device!
    @device = Device.find_by(token: request.headers['auth-token'])
    raise_unauthorized and return if @device.blank?
  end

  # Image url converters
  def image_url(url)
    APPURL + url
  end

  def shop_need_to_upgrade
    render json: { status: 0, code: 401, data: nil,
                   message: 'Shop Subscription need to upgrade' }
  end


  def raise_unauthorized
    render json: { status: 0, code: 401,
      response_code: 1008, data: nil,
      message: 'Unauthorized' }
  end

  def raise_check_params
    render json: { status: 0, code: 400, response_code: 1009,data: nil,
      message: 'Please check request params' }
  end

  def raise_mandatory_params
    render json: { status: 0, code: 422,
      response_code: 1010, data: nil,
      message: 'Missing mandatory params' }
  end

  def raise_bad_request(obj)
    errors = obj.errors.full_messages
    render json: { status: 0, code: 400, response_code: 1011, data: nil,
    message: errors.is_a?(Array) ? errors.first : errors }
  end

  def record_not_found
    render json: { status: 0, code: 404,
      response_code: 1012, data: nil,
      message: 'record Not Found' }
  end

  def raise_unprocessable_entry
    render json: { status: 'Unprocessable Entity', code: 422, response_code: 1013, data: nil,
    message: 'Unprocessable Entity' }
  end

  def render_500
    render json: { status: 'Internal Server Error', code: 500, response_code: 1014,
      data: nil, message: 'Internal Server Error' }
  end

  def set_locale
    if params[:locale]
      I18n.locale = params[:locale]
    else
      I18n.locale = :en
    end
  end
end

under /vi/

[code language=”ruby”]
class Api::V1::CategoriesController < Api::ApiController
before_action :get_menu, only: [:get_lists]
#get menu list
def get_lists
end

private
def get_menu
@shop.menus.find(params[:menu_id])
end
end
[/code]

routes :

[code language=”ruby”]
namespace :api, defaults: { format: :json } do
scope ‘v1’, module: :v1 do
namespace :devices do
post :login
end
end
end
[/code]

Strong parameters

[code language="ruby"]
def user_params
    params.require(:user).permit(:name, :phone, 
      projects_attributes: [:user_id,:name,:description,:website_url,:responsibilities,  :_destroy, :id], skills: []
      )
  end

  def subscription_params
    params.permit(:order_number, :currency_code, :invoice_id, :pay_method, :total)
  end
[/code]
[/et_pb_text][/et_pb_column] [/et_pb_row] [/et_pb_section]