How To Use Constructor in Rails

Constructor This is how to create constuctor for you to use in your Rails /lib class, model class, etc. Below is the sample contructor I made for you as a guide.
  
  class Person
    attr_accessor :firstname, :lastname, :age

    def initialize(attributes = {})
     self.firstname = attributes[:firstname]
     self.lastname = attributes[:lastname]
     self.age = attributes[:age]
    end

    def fullname
     "#{firstname} #{lastname}"
    end

    def full_info
     "My name is #{firstname} #{lastname}. And I am already #{age} years old."
    end
  end
  
To test, first you should initialize the object. You could test it via rails console.
  
 p = Person.new({firstname: 'oj', lastname: 'dq', age: 28})
  
Or:
  
 p = Person.new(firstname: 'oj', lastname: 'dq', age: 28)
  
To run it should be:
  
 p.age
 p.firstname.nil?
 p.fullname
  
There's other way to use constructor. It is how to mix your model (ActiveRecord). Below, I wrote a simple class which is refer to User Model. Mix ActiveRecord
  
  require 'model_you_want_to_use' # for example Atricle require 'artricle'

  module Application
   module Backend
    class Users
    attr_accessor :user_id

    def initialize(attributes = {})
     self.user_id = attributes[:user_id]
    end

    def fullname
     [user.first_name, user.last_name].join(' ')
    end

    def position
     user.position
    end

    def department
     user.department
    end

    private
     def user
      User.find(user_id)
     end
    end
   end
  end

  
The question is how to use this? First you should call by using require method of Ruby.
  
  require 'application/backend/users'
  
To initialize:
  
  users = Application::Backend::Users.new(user_id: 1)
  
And now, using users variable, you can call the methods defined in Application->Backend->Users class.
  
  users.fullname
  
If you want to add some params in initialization, you should notice the following. Please compare difference when I want to add params. In this case, I want to add parameter called current_link.
  
  attr_accessor :user_id, :current_link

  def initialize(attributes = {})
  self.user_id = attributes[:user_id]
  self.current_link = attributes[:current_link]
  end
  
And now you can call the parameter current_link in any methods inside the class. For example:
  
  
  def fullname_with_link
   "https://localhost:3000/users/#{[user.first_name, user.last_name].join(' ')}"
  end
  
  # Or call the link itself.
  def current_link
   current_link
  end
  

No comments:

Post a Comment