Skip to content

Instantly share code, notes, and snippets.

Ways to Call a Function

Let's review the various ways to call a function that we have encountered:

  • Function-style when unbound (fun(arg1, arg2))
    • this is set to the global context (global or window)
  • Method-style (obj.method(arg1, arg2))
    • this is set to obj
  • Constructor-style (new ClassName(arg1, arg2)).
    • Creates a new, blank object.
@jeffnv
jeffnv / super_attrs.rb
Created October 30, 2014 17:10
a working model of ActiveRecord attribute accessor methods
class ARBase
def self.already_built_attr_methods?
@already_built_attr_methods
end
def method_missing name, *args
unless self.class.already_built_attr_methods?
self.class.build_attr_methods
#try it again
self.send(name, *args)
class Gist < ActiveRecord::Base
attr_accessible :title, :user_id, :gist_files_attributes, :tags_attributes
belongs_to :user
has_many :favorites
has_many :gist_files
has_many :taggings
has_many :tags, through: :taggings, source: :tag
accepts_nested_attributes_for :gist_files, :tags
end
def create
current_user.friend_ids = params[:friend_ids]
current_user.save
redirect_to friend_circles_url
end
def create
@user = User.find_by_credentials(params[:user][:user_name], params[:user][:password])
if @user.nil?
flash[:errors] = ["Credentials were wrong"]
render :new
else
self.current_user = @user
redirect_to cats_url
end
def self.contacts_for_user_id(user_id)
c = Contact.joins(<<-SQL)
LEFT JOIN contact_shares cs ON cs.contact_id = contacts.id
SQL
c.where("contacts.user_id = ? OR cs.user_id = ?" , user_id, user_id)
end
def has_many(name, params = {})
hsp = HasManyAssocParams.new(name, params, self.class)
assoc_params[name] = hsp
define_method(name.to_sym) do
sql = <<-SQL
SELECT *
FROM #{hsp.other_table} other
WHERE other.#{hsp.params[:foreign_key]} = ?
SQL
many = DBConnection.execute(sql, self.id)
def results
responses = Question.joins(<<-SQL)
LEFT OUTER JOIN answer_choices
ON answer_choices.question_id = questions.id
LEFT OUTER JOIN responses
ON answer_choices.id = responses.answer_choice_id
SQL
responses = responses.where("questions.id = ?", self.id)
p responses
responses.group('answer_choices.answer_body').count('responses.id')
def avg_karma
results = QuestionsDatabase.instance.execute(<<-SQL, @id, @id)
SELECT (COUNT(questions.id) *1.0/ (SELECT COUNT(*) FROM questions WHERE user_id = ?))
FROM questions JOIN question_likes ON (question_likes.question_id = questions.id)
WHERE questions.user_id = ?
SQL
results[0].values[0]
end
SELECT a.company, a.num, a.stop, b.stop
FROM route a JOIN route b ON
(a.company=b.company AND a.num=b.num)
WHERE a.stop=53