Skip to content

Instantly share code, notes, and snippets.

View vinhnglx's full-sized avatar
👓
Code is fun

Vincent Nguyen vinhnglx

👓
Code is fun
View GitHub Profile
@vinhnglx
vinhnglx / User.rb
Last active August 29, 2015 14:01
An simple example about attr_accessor
class User
attr_accessor :first_name, :last_name, :birthday
end
# Results
# user = User.new
# user.first_name = "Vinh"
# user.first_name => "Vinh"
@vinhnglx
vinhnglx / method_missing.rb
Last active August 29, 2015 14:01
An example about method_missing()
class User
attr_accessor :first_name, :last_name, :birthday
end
# Results
# user = User.new
# user.middle_name ==> NoMethodError
@vinhnglx
vinhnglx / defining_method_missing.rb
Created May 8, 2014 08:41
An example about defining method_missing()
class User
attr_accessor :first_name, :last_name, :birthday
# method_missing() is passed 2 arguments: name of the missing method and arrays of its arguments
# reference at the link: http://www.ruby-doc.org/core-2.1.0/BasicObject.html#method-i-method_missing
def method_missing(name, *arg)
puts "#{name} was called with arguments: #{arg.join(',')}. #{name} method not available."
end
end
@vinhnglx
vinhnglx / question_answer.rb
Last active August 29, 2015 14:01
Pros of missing_method()
class Question
def get_question_title
puts "get_question_title called"
end
def get_question_content
puts "get_question_content called"
end
end
# ====================
# Spell: Dynamic Proxy
# ====================
# Forward to another object any messages that don’t match a method.
class MyDynamicProxy
def initialize(target)
@target = target
end
config.generators.stylesheet_engine = :sass
module DefaultValues
def has_default_values(default_values = {})
class_attribute :default_values
self.default_values = default_values
after_initialize :assign_default_values
include InstanceMethods
class AddNameToUser < ActiveRecord::Migration
def self.up
add_column :users, :name, :string
User.reset_column_information
User.find(:all).each do |user|
user.name = user.first_name + ' ' + user.last_name
end
remove_column :users, :first_name
remove_column :users, :last_name
end
@vinhnglx
vinhnglx / file0.rb
Last active August 29, 2015 14:06
Using Metaprogramming to refactor code ref: http://qiita.com/vinhnguyenleasnet/items/3c96930a7b48786e81cf
class User < ActiveRecord::Base
validate_inclusion_of :activation_state, :in => ["pending", "active"]
def self.pending_users
find :all, :conditions => {:activation_state => 'pending'}
end
def self.active_users
find :all, :conditions => {:activation_state => 'active'}
end
@vinhnglx
vinhnglx / contact.html.erb
Last active August 29, 2015 14:06
Using Omnicontacts to get mail contacts from Google ref: http://qiita.com/vinhnguyenleasnet/items/53ade9f730d21a7a84d4
<% unless @contacts.nil?%>
<% @contacts.each do |c|%>
<ul>
<li><%= c[:name]%> : <%= c[:email]%></li>
</ul>
<%end%>
<%end%>