[Rails] What is the question mark inside this regex doing?

2014-08-14 Thread 'John Merlino' via Ruby on Rails: Talk
I thought the ? matches zero or one occurrence of a pattern. However in 
this example:

def show_regexp(string, pattern)
  match = pattern.match(string)
  if match
#{match.pre_match}-#{match[0]}-#{match.post_match}
  else
no match
  end
end

a = The moon is made of cheese
show_regexp(a, /\s.*?\s/) #= The- moon -is made of cheese

What exactly is the ? doing?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/8d5efdaa-d690-4a34-8a84-e7c1c3696dd3%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[Rails] capistrano: deploying production and staging to same database

2014-05-01 Thread 'John Merlino' via Ruby on Rails: Talk
I have the production and staging site on two different server ips. But the 
database, another server ip, is the same database used by both production 
and staging. When i set up the capistrano deploy task for both the 
production and staging, should I keep the db role in deploy.rb like this:

deploy.rb

role :db,  database_ip, :primary = true 


production.rb

role :web, production_ip 
role :app, production_ip  

staging.rb

role :web, staging_ip 
role :app, staging_ip  

Or should I do it this way:

production.rb

role :web, production_ip 
role :app, production_ip  

role :db,  database_ip, :primary = true 


staging.rb

role :web, production_ip 
role :app, production_ip  

role :db,  database_ip, :primary = true 


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/f4494c9d-b537-4e7e-b92f-b50f56520870%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[Rails] staging server unexpectedly started installing gems during staging deploy

2014-05-01 Thread 'John Merlino' via Ruby on Rails: Talk
I have  a production server and a staging server and a production git 
branch and a staging git branch for the same repository on github. The 
production git branch and staging git branch are identical. I got my 
staging server running and during the second deploy, something unexpected 
started happening:

...
 ** [out :: xxx.xx.xx.xxx] Installing multi_json (1.5.0)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing activesupport (3.2.5)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing builder (3.0.4)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing activemodel (3.2.5)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing erubis (2.7.0)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing journey (1.0.4)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing rack (1.4.1)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing rack-cache (1.2)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing rack-test (0.6.2)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing hike (1.2.1)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing tilt (1.3.3)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing sprockets (2.1.3)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing actionpack (3.2.5)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing mime-types (1.19)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing polyglot (0.3.3)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing treetop (1.4.12)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing mail (2.4.4)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing actionmailer (3.2.5)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing active_record-tableless_model (0.0.1)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing arbre (1.0.1)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing sass (3.2.4)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing thor (0.16.0)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing bourbon (3.0.1)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing bcrypt-ruby (3.0.1)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing orm_adapter (0.4.0)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing rack-ssl (1.3.2)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing json (1.7.6)
 ** [out :: xxx.xx.xx.xxx] 
 ** [out :: xxx.xx.xx.xxx] Installing rdoc (3.12)

It started installing gems. What I don't understand is why it did this 
during second deploy and not first? My staging and production gems should 
be identical. My deploy.rb file has this:

namespace :deploy do
  desc Create the gemset
  task :create_gemset do
run rvm #{rvm_ruby_string} --create
  end

  desc Install the bundle
  task :bundle do
run bundle install --gemfile #{release_path}/Gemfile --without 
development test
  end
end

Now the bundle install there should only be installing new gems that are 
added. But I didn't add any new gems during this deploy. Any idea why the 
capistrano task started installing the above gems?



-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/2c7ebacd-8b58-4cfb-88f1-e356072fe1f1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[Rails] redis, pub/sub, rails 3, phusion passenger

2014-03-18 Thread John Merlino
I have another application publishing messages to redis server. Within my 
rails application, when a user clicks a button, I want a popup to display 
that shows live updates. I want the controller to publish notifications to 
redis, and I want my javascript to subscribe to those events and respond 
when it finds a suitable channel. What I do not know how to do is actually 
keep a control open like that: to continuously publish messages when it 
finds them on redis. Is this possible to do in rails 3/phusion passenger?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/a1090c0c-8196-4fa7-87e6-3eeaac45bbfe%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[Rails] find_by_sql query running incredibly slow

2014-03-04 Thread John Merlino
Initially, I was using this query:


report_ids = []
if units.size  0
  units.map(:id).uniq.each do |id|
report_id = Report.select(:id).where(unit_id: id).order(time 
desc).first
unless report_id.nil?
  report_ids  report_id
end
  end
end
reports = Report.where(id: report_ids).order(longitude desc)

It looks sloppy, and it took around 7 or 8 seconds to load all the data.

So I wanted to create a cleaner, quicker query, so I tried this:

reports = Report.find_by_sql([SELECT DISTINCT ON (unit_id) r.* 
  FROM reports r 
  WHERE r.unit_id IN (?) 
  ORDER BY unit_id, time DESC, 
  units.map(:id)])

But this is running incredibly slow. In fact, after 15 minutes, I just 
cancelled the process. 


Any idea why the second query is taking markedly  longer than the first?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/cd947975-2605-432d-bdfb-6e25be66e806%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


[Rails] Optimize query to use sql over ruby iterators

2014-02-24 Thread John Merlino
I have the following setup:

class Unit
  has_many :reports
end

class Report
  belongs_to :unit
end

Basically I have a list of units and I want to select the last report for 
each unit (based on time) and order the resulting last reports by longitude.

Sounds simple, but my implementation looks like this:

units = current_user.accessible_units
report_ids = []
if units.size  0
  units.map(:id).uniq.each do |id|
report = Report.select(:id).where(unit_id: id).order(time 
desc).limit(1)
if !report.empty?
  report_ids  report.try(:first).try(:id)
end
  end
end
reports = Report.where(id: report_ids).order(longitude desc)

Is there a way to perform this same query using sql (active record 
relations) and minimize the use of ruby iterators, like map and each? Also 
notice in query above, I make two hits to the database by querying reports 
for time and then descending order. Is there a way to eliminate that too?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/dcd64657-0231-4d6a-ad24-6eab7466a493%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


[Rails] difference between Self joins and self-referential association

2013-12-07 Thread John Merlino
self-joins are discussed here:
http://guides.rubyonrails.org/association_basics.html#self-joins

self-referential association is discussed here:
http://railscasts.com/episodes/163-self-referential-association

The main difference I see is that self-referential association creates a 
join model, such as friendship, which links another model, such as user, to 
itself, so a user can have many friends (which are other users), and a 
friend can be befriended by a user. The self-joins looks like there is no 
join model. Simply a foreign key is added to the same model, such as a 
manager_id column to the employee model. An employee, who is a manager, can 
have many other employees, who are subordinates. And the link is done on 
the same table itself, association the employee manager_id column with the 
the employee id column. To me, these two techniques look virtually the 
same. Is there a difference and which is preferred? 

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/bdd46a05-4cbe-4db3-ac90-679ffbdfedd5%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


[Rails] I have bloat. Should I use Rack::Bug, MemoryLogic or Oink on Rails 3 app?

2013-12-04 Thread John Merlino
I have severe bloat, spending most of the day killing rack processes on my 
server. I need to figure out the cause. Most likely too many activerecord 
objects allocated in memory, to the point that rock process exceeds 1 gig 
of private dirty memory. Should I use Rack::Bug, MemoryLogic or Oink on 
Rails 3 app to pinpoint the problem?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/50c2755f-5068-4590-b71a-3c9d7ddad996%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


[Rails] rails and passenger memory issues

2013-12-03 Thread John Merlino
I'm using Rails 3, Passenger, and Postgresql. Yesterday the rails 
application was running very slow. So I rebooted the server. Less than 24 
hours later, it is consuming even more memory than before and when trying 
to load the web page, it just hangs forever. I ran passenger-memory-stats 
to inspect the issue. And once again, I notice 2 rack processes using over 
2 gigabytes of private dirty RSS:


$ rvmsudo -E /usr/local/rvm/gems/ruby-1.9.3-p327/bin/passenger-memory-stats
Use of uninitialized value $includedir in concatenation (.) or string at 
(eval 9) line 1.
Use of uninitialized value $includedir in concatenation (.) or string at 
(eval 9) line 1.

- Apache processes --
PIDPPID  VMSizePrivate  Name
-
1079   1 145.6 MB  0.3 MB   /usr/sbin/apache2 -k start
2163   1079  160.5 MB  15.2 MB  /usr/sbin/apache2 -k start
2450   1079  145.9 MB  0.5 MB   /usr/sbin/apache2 -k start
5638   1079  161.1 MB  15.8 MB  /usr/sbin/apache2 -k start
6923   1079  145.8 MB  0.4 MB   /usr/sbin/apache2 -k start
9829   1079  160.0 MB  14.9 MB  /usr/sbin/apache2 -k start
11016  1079  160.5 MB  15.3 MB  /usr/sbin/apache2 -k start
11097  1079  160.5 MB  15.3 MB  /usr/sbin/apache2 -k start
11948  1079  145.8 MB  0.4 MB   /usr/sbin/apache2 -k start
11961  1079  145.8 MB  0.3 MB   /usr/sbin/apache2 -k start
11969  1079  145.8 MB  0.3 MB   /usr/sbin/apache2 -k start
12460  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
12461  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
12462  1079  145.7 MB  0.2 MB   /usr/sbin/apache2 -k start
12491  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
12533  1079  157.5 MB  14.4 MB  /usr/sbin/apache2 -k start
12535  1079  159.8 MB  14.6 MB  /usr/sbin/apache2 -k start
12536  1079  157.7 MB  14.3 MB  /usr/sbin/apache2 -k start
12552  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
12717  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
12757  1079  150.1 MB  4.6 MB   /usr/sbin/apache2 -k start
12990  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
13015  1079  150.3 MB  5.2 MB   /usr/sbin/apache2 -k start
13016  1079  159.8 MB  14.4 MB  /usr/sbin/apache2 -k start
13045  1079  147.9 MB  4.3 MB   /usr/sbin/apache2 -k start
13046  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
13047  1079  152.4 MB  8.9 MB   /usr/sbin/apache2 -k start
13288  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
13324  1079  152.4 MB  8.9 MB   /usr/sbin/apache2 -k start
13329  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
13331  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
13959  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
13960  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
13961  1079  149.0 MB  3.8 MB   /usr/sbin/apache2 -k start
14037  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14040  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14051  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14052  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14053  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14059  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14061  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14069  1079  148.7 MB  3.4 MB   /usr/sbin/apache2 -k start
14089  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14127  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14132  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14149  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14481  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14548  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14552  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14553  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14554  1079  146.7 MB  3.4 MB   /usr/sbin/apache2 -k start
14555  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14556  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14557  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14593  1079  148.8 MB  3.6 MB   /usr/sbin/apache2 -k start
14594  1079  159.8 MB  14.4 MB  /usr/sbin/apache2 -k start
14606  1079  146.7 MB  3.4 MB   /usr/sbin/apache2 -k start
14792  1079  149.0 MB  3.8 MB   /usr/sbin/apache2 -k start
14808  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14914  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14915  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14917  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14918  1079  145.9 MB  0.3 MB   /usr/sbin/apache2 -k start
14920  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14927  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14997  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
14998  1079  159.7 MB  14.4 MB  /usr/sbin/apache2 -k start
14999  1079  149.0 MB  3.8 MB   /usr/sbin/apache2 -k start
15016  1079  145.6 MB  0.2 MB   /usr/sbin/apache2 -k start
15239  1079  145.9 MB  0.4 MB   /usr/sbin/apache2 -k start
15244  1079  145.9 MB  0.3 MB   /usr/sbin/apache2 -k start
15249  1079  145.6 MB  0.2 MB   

[Rails] find total months passed between two ActiveSupport::TimeWithZone objects

2013-09-26 Thread John Merlino
unit.created_at.class
 = ActiveSupport::TimeWithZone 

 Time.zone.now.class
 = ActiveSupport::TimeWithZone 


 Time.zone.now - unit.created_at
 = 47709736.32316899 

I think that's the number of seconds that have passed between when the unit 
was created and the current time. Is this correct? If so, is there any 
easier way to find the total months that passed between two time objects 
like this?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/ee22138c-7949-4ebb-b1d6-1776362c4f99%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


[Rails] DateTime now

2013-09-15 Thread John Merlino
When using DateTime.now, does the now method return the time based on the 
remote OS system time or the local time where the user actually invoked the 
now method, if they are using ssh and running the commands in a rails 
console, for example?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/46b3432f-5ab4-42f8-9ac2-1ea8bb30cbb0%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


[Rails] rails is not to logging controller, action, parameters, complection time, etc in development mode

2013-07-22 Thread John Merlino
For this one particular project, rails is not to logging controller, 
action, parameters, complection time, etc in development mode. And I am not 
sure why.

When I check in the console the log level I notice:

Rails.logger.level
 = 0 

So I am not sure why it doesn't log the information it usually does during 
a request. 


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/ae27ecd7-90a7-44c2-a6bc-c0282e6f3518%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] installing rvm in home directory or system-wide?

2013-07-16 Thread John Merlino
Is there any advantages of installing rvm system-wide as opposed to just in 
the home directory of a user?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/0a7e0bb6-2e4c-44be-90e6-12099105d787%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Does each ip request to a ruby on rails application on a server spawn a new ruby process?

2013-07-10 Thread John Merlino
When I view the output of the top command on ubuntu, I notice sometimes 
there is 6 ruby processes. When are each of these processes spawned?

http://tinypic.com/view.php?pic=2i24rwhs=5

I cannot imagine that it's every time someone loads the rails application 
from a different ip address, otherwise I would assume there would be more 
ruby processes spawned. 

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/594957ab-4038-43c2-883d-640f26599541%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] cap deploy:setup fails

2013-06-25 Thread John Merlino
I run cap deploy:setup

And towards the end, I see the following issues:

** [out :: xxx.xx.xx.132] Unrecognized command line flag: 
'--autolibs=read-only' ( see: 'rvm usage' )
 ** [out :: xxx.xx.xx.134] Already installed ruby-1.9.3-p0.
 ** [out :: xxx.xx.xx.134] To reinstall use:
 ** [out :: xxx.xx.xx.134] 
 ** [out :: xxx.xx.xx.134] rvm reinstall ruby-1.9.3-p0
 ** [out :: xxx.xx.xx.134] 
 ** [out :: xxx.xx.xx.132] Ruby ruby-1.9.3-p0 is not installed.
 ** [out :: xxx.xx.xx.134] gemset created spree_ecommerce = 
/usr/local/rvm/gems/ruby-1.9.3-p0@spree_ecommerce
command finished in 931ms
failed: bash -c '__LAST_STATUS=0; export 
CURL_HOME=\${TMPDIR:-${HOME}}/.rvm-curl-config.$$\; mkdir ${CURL_HOME}/; 
{ [[ -r ${HOME}/.curlrc ]]  cat ${HOME}/.curlrc; echo \silent\; echo 
\show-error\; }  $CURL_HOME/.curlrc; sudo -p '\\''sudo password: '\\'' 
sg rvm -c \/usr/local/rvm/bin/rvm --autolibs=read-only install 
ruby-1.9.3-p0 -j $(cat /proc/cpuinfo 2/dev/null | (grep vendor_id || echo 
'\\''vendor_id : Other'\\'';) | wc -l) \; sudo -p '\\''sudo password: 
'\\'' sg rvm -c \/usr/local/rvm/bin/rvm ruby-1.9.3-p0 do rvm gemset create 
spree_ecommerce\ || __LAST_STATUS=$?; rm -rf $CURL_HOME; exit 
${__LAST_STATUS}' on xxx.xx.xx.132

Note that I have another rails application, that deploys fine, whose deploy 
configuration is very very similar. Here's the deploy.rb:

require 'capistrano/ext/multistage'
require rvm/capistrano
require 'bundler/capistrano'

after deploy:update_code, deploy:symlink_shared_configs
load 'deploy/assets'

set :application, SpreeSite

set :stages, [staging, production]
set :default_stage, production

set :scm, git
set :repository,  g...@github.com:MyAccount/SpreeSite.git
set :branch, master
default_run_options[:pty] = true

role :web, xxx.xx.xx.134  # Your HTTP server, 
Apache/etc
role :app, xxx.xx.xx.134  # This may be the 
same as your `Web` server
role :db,  xxx.xx.xx.132, :primary = true# This is where 
Rails migrations will run

set :deploy_to, ~/public_html/mysite.com/

set :user, ubuntuuser
set :use_sudo, false

set :deploy_via, :remote_cache

set :rvm_ruby_string, 'ruby-1.9.3-p0@spree_ecommerce' #this failed on 
remote server when using ruby-1.9.3@spree_ecommerce !! 
set :rvm_autolibs_flag, read-only

set :rvm_type, :system
set :rvm_install_with_sudo, true

before 'deploy:setup', 'rvm:install_rvm'   # install RVM
before 'deploy:setup', 'rvm:install_ruby'  # install Ruby and create 
gemset, OR:
before 'deploy:setup', 'rvm:create_gemset' # only create gemset
 
# If you are using Passenger mod_rails uncomment this:
 namespace :deploy do
   desc Symlink configuration files
   task :symlink_shared_configs, :roles = [:db,:app] do
 run ln -nfs #{shared_path}/config/database.yml 
#{release_path}/config/database.yml
   end
 
   task :start do ; end
   task :stop do ; end
   task :restart, :roles = :app, :except = { :no_release = true } do
 run #{try_sudo} touch 
#{File.join(current_path,'tmp','restart.txt')}
   end
 end

#deploy/production.rb:

set :deploy_to, /home/ubuntuuser/public_html/mysite.com/
set :rails_env, 'production'

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/5c19417a-45e3-4d0a-8dff-980ca22d513d%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] ruby pack unexpected results

2013-06-24 Thread John Merlino
I have two hex values and expect back the value 3007


What pack does is take the array of hexes and formats them into a string 
(if ASCII representation, then ASCII character, otherwise the raw hex as 
string). Then I take the string of hexes and unpack them, that is, get the 
unsigned int representation of those bytes:
[0xBF, 0xB].pack('C*').unpack('I')[0]

So I expect back 3007, but the above produces nil.

This is what I want to achieve:

[0xBF, 0xB].reverse.inject { |s,v| s * 256 + v }
 = 3007 

But I want to use unpack instead of inject.


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/4d8e50a7-dc9e-4da9-b8e3-bc4ba4f5c62f%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] uninstall dependencies along with the gem

2013-06-22 Thread John Merlino
I installed spree by adding it in gemfile. It was giving me errors, so I 
went to the github site, and installed spree using gem install spree. But 
now it looks like i have two sets of gems for the dependencies of spree:

spree_api (2.0.3, 0.40.0)
spree_auth (0.40.0)
spree_backend (2.0.3)
spree_cmd (2.0.3)
spree_core (2.0.3, 0.40.0)
spree_dash (0.40.0)
spree_frontend (2.0.3)
spree_promo (0.40.0)
spree_sample (2.0.3, 0.40.0)


How do I uninstall spree and all of the gems that were installed along with 
it?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/f9d6b22c-7d2d-4a0d-951f-62904f3d09f4%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] yaml and ip addresses

2013-05-21 Thread John Merlino
I was using this code

url = http://#{agent_host}:#{agent_port}/home/create_unit?;


And it worked fine in development but for my config.yml, I was
specifying localhost for agent_host. However in production, agent_host
is an actual ip address and it just wouldn't work. So I had to
explicitly put the ip address in production:

url = http://xxx.xxx.xx.xxx/home/create_unit?;

This is what that config file had:

agent_development:
  host: localhost
  port: 3001
agent_production:
  host: xxx.xxx.xx.xxx
  port: 80
agent_staging:
  host: xxx.xxx.xx.xxx
  port: 80

where the x's are replaced with actual numeric values that represent
ip address.

How does the yaml interpret that ip address? As a decimal value? I'm
not sure why when I substitute it into the string interpolation, that
it doesn't in production.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/a2164b5e-4180-4f74-aa06-0f6ecd8ffef8%40w15g2000vbn.googlegroups.com?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] undefined method `stringify_keys' for #String:0x007fe8a3ba0a48

2013-05-20 Thread John Merlino
From my understanding, you can pass a block to the link_to helper, but
the following code gives me an error undefined method
`stringify_keys' for #String:0x007fe8a3ba0a48.

= link_to(One time Payment with Paypal or Credit Card,
@order.payment_payment_standard_url(new_order_url(invoice: @invoice),
payment_notifications_url, @invoice)) do
  = image_tag https://www.paypalobjects.com/webstatic/
mktg/logo/AM_mc_vs_dc_ae.jpg

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/b58db872-c5b1-4bea-b7a6-9ec52f856ff6%40r3g2000yqe.googlegroups.com?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] relationship of shopping cart and order

2013-05-19 Thread John Merlino
Most implementations of shopping carts I have seen is that a user
stores line items in a cart, where the line items represent products
or subscriptions. So a cart has many products through line items and a
product can have many carts through line items. Then a customer makes
an order and so you introduce a new model order. The order has
information such as customer's name, the payment type, and if you are
working with a payment gateway, such as paypal, it will contain paypal
tokens and recurring tokens. So the order and the cart are two
different models, two different purposes. Cart is a thing that enables
a customer to store things in, and a order is the thing that handles
payments. So I was watching this railscasts and he updates a
purchased_at attribute on the cart itself:

http://railscasts.com/episodes/142-paypal-notifications?view=comments

But is a cart really purchased, or is it the order that is purchased?
If the order contains all payment information, shouldn't the order
contain the purchased_at attribute and not the cart?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] You have already activated rake 10.0.4, but your Gemfile requires rake 10.0.3.

2013-05-18 Thread John Merlino
I'm careful to create separate gemsets for each project, so when I run
bundle install, it only installs gems for that gemset. This way gems
dont creep into the wrong projects. Now I just pulled a project from
github. I made sure I was in the correct gemset, and then I run bundle
install and it works fine. but then when I use rake to create the
database rake db:create. I get this error:

You have already activated rake 10.0.4, but your Gemfile requires rake
10.0.3.

What does it mean you already activated rake 10.0.4? All that should
be installed for this gemset is whatever is in Gemfile.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] staging deploy connected to production database

2013-05-15 Thread John Merlino
I'm not sure why but I have both a staging and production deploy using
the 'capistrano/ext/multistage' gem. I set staging to the default:

set :stages, [staging, production]
set :default_stage, staging

It deploys correctly to the right path:
#deploy/staging.rb
set :deploy_to, /home/myuser/public_html/mysite/

But it connects to the production database not staging database in my
database.yml file:

staging:
  adapter: mysql2
  encoding: utf8
  database: staging_database
  pool: 5
  username: username
  password: password
  socket: /var/run/mysqld/mysqld.sock
  host: host

production:
  adapter: mysql2
  encoding: utf8
  database: production_database
  pool: 5
  username: username
  password: password
  socket: /var/run/mysqld/mysqld.sock
  host: host

Why is it linking to the production database and not staging? I don't
see where that option is specified during the deploy process.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] rvm/capistrano

2013-05-14 Thread John Merlino
When I ran cap deploy:setup, the following actually installed rvm,
ruby and the online_store gemset on my staging server:

set :rvm_ruby_string, 'ruby-1.9.3-p0@online_store'
set :rvm_autolibs_flag, read-only

set :rvm_type, :system
set :rvm_install_with_sudo, true

before 'deploy:setup', 'rvm:install_rvm'   # install RVM
before 'deploy:setup', 'rvm:install_ruby'  # install Ruby and create
gemset, OR:
before 'deploy:setup', 'rvm:create_gemset' # only create gemset

Now that's what you would expect. However, I already had rvm, ruby
installed on my server, and all I wanted installed was the gemset
called online_store. So why was this unable to detect that rvm and
ruby was already installed?


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] capistrano/mod_rails

2013-05-14 Thread John Merlino
I was following these instructions for capistrano deployment:

https://github.com/capistrano/capistrano/wiki/2.x-From-The-Beginning

Under the section Application Layer Initialization, it says:

We need to tell Capistrano how to “spin up” (start) our application
layer. The precise way this works will vary depending on how you’re
running your application layer. If you’re using mod_rails, for
instance, it will be very different than if you’re using mongrel.
Here, I’ll assume you’re using mongrel. By default, when Capistrano
needs to start your application layer, it will try to execute a script
called “spin”, in the “script” directory of your application, on each
remote server. We’ll need to write that script, and then check it into
the source repository.

Well I'm using mod_rails/passenger. Do I need to be writing any
scripts as it suggests when using mod_rails?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] patch levels and ruby

2013-05-14 Thread John Merlino
How do you know which patch level to use for ruby? I have one project that 
uses ruby-1.9.3-p0. When I cd into another project, it 
says: ruby-1.9.3-p392 is not installed. So which to use: ruby-1.9.3-p0 
or ruby-1.9.3-p392?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/e795aa06-bf20-482b-9443-1df67fa1a1bb%40googlegroups.com?hl=en-US.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: patch levels and ruby

2013-05-14 Thread John Merlino
I'm using capistrano. I added this to the recipe:

set :rvm_ruby_string, 'ruby-1.9.3-p0@online_store'   # use
the same ruby as used locally for deployment
set :rvm_autolibs_flag, read-only# more info: rvm help
autolibs

set :rvm_type, :system
set :rvm_install_with_sudo, true

before 'deploy:setup', 'rvm:install_rvm'   # install RVM
before 'deploy:setup', 'rvm:install_ruby'  # install Ruby and create
gemset, OR:
before 'deploy:setup', 'rvm:create_gemset' # only create gemset


Thats why patch level p0 is there. If I drop the -p0, will it install
the latest rvm with each cap deploy?

On May 14, 12:53 pm, Walter Lee Davis wa...@wdstudio.com wrote:
 On May 14, 2013, at 12:37 PM, John Merlino wrote:

  How do you know which patch level to use for ruby? I have one project that 
  uses ruby-1.9.3-p0. When I cd into another project, it says: 
  ruby-1.9.3-p392 is not installed. So which to use: ruby-1.9.3-p0 or 
  ruby-1.9.3-p392?

 Personally, with the rash of security updates we have seen lately, I would 
 always use the latest Ruby you can in your major branch. Make sure your tests 
 pass in the app that runs on v.0, and then update to the latest and run them 
 again. If you're using rvm, that's likely how you got locked into v.0 and 
 v.[whatever] in two different apps. If so, then check to see if you have an 
 .rvmrc file in that folder. (Or local equivalent for some other 
 ruby-switcher.)

 Walter









  --
  You received this message because you are subscribed to the Google Groups 
  Ruby on Rails: Talk group.
  To unsubscribe from this group and stop receiving emails from it, send an 
  email to rubyonrails-talk+unsubscr...@googlegroups.com.
  To post to this group, send email to rubyonrails-talk@googlegroups.com.
  To view this discussion on the web 
  visithttps://groups.google.com/d/msgid/rubyonrails-talk/e795aa06-bf20-482b
  For more options, visithttps://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: patch levels and ruby

2013-05-14 Thread John Merlino
My /usr/local/rvm/gems looks like this (on ubuntu server):

cache  ruby-1.9.3-p0@globalruby-1.9.3-p194
ruby-1.9.3-p194@TrackingSystem
ruby-1.9.3-p0  ruby-1.9.3-p0@online_store  ruby-1.9.3-p194@global
ruby-1.9.3-p392@TrackingSystem

Is this normal to be using so many patch levels? Obviously I want
different gemsets for different projects to manage with bundler. But
patch levels?

On May 14, 1:06 pm, John Merlino stoici...@aol.com wrote:
 I'm using capistrano. I added this to the recipe:

 set :rvm_ruby_string, 'ruby-1.9.3-p0@online_store'               # use
 the same ruby as used locally for deployment
 set :rvm_autolibs_flag, read-only        # more info: rvm help
 autolibs

 set :rvm_type, :system
 set :rvm_install_with_sudo, true

 before 'deploy:setup', 'rvm:install_rvm'   # install RVM
 before 'deploy:setup', 'rvm:install_ruby'  # install Ruby and create
 gemset, OR:
 before 'deploy:setup', 'rvm:create_gemset' # only create gemset

 Thats why patch level p0 is there. If I drop the -p0, will it install
 the latest rvm with each cap deploy?

 On May 14, 12:53 pm, Walter Lee Davis wa...@wdstudio.com wrote:







  On May 14, 2013, at 12:37 PM, John Merlino wrote:

   How do you know which patch level to use for ruby? I have one project 
   that uses ruby-1.9.3-p0. When I cd into another project, it says: 
   ruby-1.9.3-p392 is not installed. So which to use: ruby-1.9.3-p0 or 
   ruby-1.9.3-p392?

  Personally, with the rash of security updates we have seen lately, I would 
  always use the latest Ruby you can in your major branch. Make sure your 
  tests pass in the app that runs on v.0, and then update to the latest and 
  run them again. If you're using rvm, that's likely how you got locked into 
  v.0 and v.[whatever] in two different apps. If so, then check to see if you 
  have an .rvmrc file in that folder. (Or local equivalent for some other 
  ruby-switcher.)

  Walter

   --
   You received this message because you are subscribed to the Google Groups 
   Ruby on Rails: Talk group.
   To unsubscribe from this group and stop receiving emails from it, send an 
   email to rubyonrails-talk+unsubscr...@googlegroups.com.
   To post to this group, send email to rubyonrails-talk@googlegroups.com.
   To view this discussion on the web 
   visithttps://groups.google.com/d/msgid/rubyonrails-talk/e795aa06-bf20-482b
   For more options, visithttps://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] manual vs automatic bundler deployment with capistrano

2013-05-14 Thread John Merlino
I assume this is the most up to date documentation for running bundler
install when deploying a rails application with capistrano:

http://gembundler.com/v1.3/deploying.html

In the documentation, it offers two methods for deploying capistrano
with bundler: manual vs automatic.

Which is preferred?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] capistrano and scm_username and github

2013-05-10 Thread John Merlino
In the capistrano wiki, it contains this line:

set :scm_username, “foo”. If you access your source repository with a
different user name than you are logged into your local machine with,
Capistrano needs to know.

Actually the way I access my repository through my app is through ssh
keys. The only user name I have with github is the one I use to log
into github to view my repositories.

So I'm not sure if scm_username is needed and what username does it
want.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Net::HTTP

2013-05-07 Thread John Merlino
I'm looking at the documentation:
http://ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/HTTP.html

And I notice two uses of Net::HTTP. Both are using GET requests. But
what's the difference? When to use which?

Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri

  response = http.request request # Net::HTTPResponse object
end



uri = URI('http://example.com/index.html')
res = Net::HTTP.get_response(uri)

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




Re: [Rails] rvm installation script

2013-05-05 Thread John Merlino
https://rvm.io/rvm/install

Look at the first line:

Install RVM with ruby (# for pretty output): 

$ \curl -#L https://get.rvm.io | bash -s stable --autolibs=3 --ruby

But later on on that page it sasy:

1. Download and run the RVM installation script 

Installing the stable release version: 
user$ \curl -L https://get.rvm.io | bash -s stable

So I assume that the addition of --autolibs=3 --ruby

means that it instlals all ruby dependencies for you so you dont have to 
run:

rvm requirements
...
# For Ruby / Ruby HEAD (MRI, Rubinius,  REE), install the following:
ruby: /usr/bin/apt-get install build-essential openssl libreadline6 
libreadline6-dev 
curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 
libxml2-dev
libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion 
pkg-config

and install those manually.

Is that correct?





On Sunday, May 5, 2013 10:41:01 AM UTC-4, Colin Law wrote:

 On 5 May 2013 00:30, John Merlino stoi...@aol.com javascript: wrote: 
  Which of these scripts is preferred to install rvm on ubuntu server: 
  
  curl -#L https://get.rvm.io | bash -s stable --autolibs=4 --ruby 

 I don't think-#L is a good idea, but I assume that is a typo 

  
  curl -L get.rvm.io | bash -s stable --auto 

 I can't see the documentation for --auto, have you got a link for it? 

 Colin 


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/6u649LpHdMgJ.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] rvm installation script

2013-05-04 Thread John Merlino
Which of these scripts is preferred to install rvm on ubuntu server:

curl -#L https://get.rvm.io | bash -s stable --autolibs=4 --ruby

curl -L get.rvm.io | bash -s stable --auto


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] where exactly are gems?

2013-04-27 Thread John Merlino
when you add a gem to the Gemfile and then run bundle install, where
does the command look for the gem? If you had gem 'rails', :git =
'github.com/rails/rails.git, I assume it would update your
system .rvm gems directory with the latest github commits. But what is
the default repository that bundler looks for gems?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] bundle.lock and production deploy

2013-04-27 Thread John Merlino
From my understanding, Gemfile.lock lists all the gems installed for
the application along with the specific versions used. This means your
app will only use the versions mentioned here and no others, even if
updates for those gems are available. When you are deploying your
application to staging or production, your application is going on a
separate server so you want to make sure all the same versions of the
gems are installed there as your local development system, so you
should use bundle lock in this situation. So does that mean when you
use capistrano to do a production deploy, and you always run bundle
install during a deploy, should you run bundle lock before you run
bundle install during the deploy process to production to make sure
that gems aren't updated in production if they are not updated in
development computer?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] mysql on different server than rails application

2013-04-27 Thread John Merlino
There's a common problem when you run bundle install and it tries to
install the msql2 gem but fails when mysql itself is not installed on
the machine. What if you have mysql installed on a different machine
(because you don't want your web application which is accessible to
the public and your mysql database on the same machine)? In this case,
do you still have to install mysql on the web application machine just
for the sole purpose of making this error go away?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] running bundle sometimes installs other gems than ones specified in Gemfile

2013-04-23 Thread John Merlino
Quick question. Often I add a gem to my Gemfile and then run bundle
install and I notice that it installs a bunch of other stuff (in
addition to what I wanted):

Installing warden (1.2.1)
Installing devise (2.2.3)
Installing fastercsv (1.5.5)
Installing formtastic (2.2.1)
Installing has_scope (0.5.1)
Installing responders (0.9.3)
Installing inherited_resources (1.4.0)

Does this mean that the gem I want to install is dependent on the
aforementioned gems?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: running bundle sometimes installs other gems than ones specified in Gemfile

2013-04-23 Thread John Merlino
So this means I don't need to add devise to my Gemfile now and run a
bundle because devise is already isntalled and fully functioning in my
app?

On Apr 23, 6:17 pm, Scott Ribe scott_r...@elevated-dev.com wrote:
 On Apr 23, 2013, at 3:52 PM, John Merlino wrote:

  Does this mean that the gem I want to install is dependent on the
  aforementioned gems?

 Yes, one of the features is that it finds and installs dependencies for you, 
 so you only have to list what you know that you're using directly, and not 
 worry about all the requirements to get to where you can use them.

 --
 Scott Ribe
 scott_r...@elevated-dev.comhttp://www.elevated-dev.com/
 (303) 722-0567 voice

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] heruko performance vs shared hosting performance

2013-04-04 Thread John Merlino
This guy is using godaddy shared hosting for his wordpress blog. I
think it's currently $5 a month. I was thinking to use Rails for his
next project. But I wouldn't want costs to exceed more than $20 per
month. I contacted heroku and they said that 1 dyno is free to host
your ruby on rails app and each additional dyno is $30 a month. A
single Heroku dyno provides 512mb ram and 1024mb swap. It has 4
(virtual) CPU cores (Intel Xeon X5550 @ 2.67GHz). 512mb ram doesn't
seem to be much, particularly for memory-intensive processing.
Although, the multiple CPU cores may enhance multi-threading. That
said, this really isn't going to be a memory hog. Now I was curious to
compare these specs with that of a shared hosting environment (where
many different customers share the same resources). For example,
godaddy says this about their shared hosting Currently there is not a
‘set number’ for CPU resources. Mostly because we have multiple
hardware platforms in the wild. Simply put, if your processes degrade
performance for other customers on the server(s) we will take actions
to protect the other customers. So that's not much of a comparison.
But does anyone have any experience on shared hosting (I know that
most shared hosting environments dont support ruby - but Im sure you
used it for other platfroms like asp.net/php) vs heroku, and if
someone is used to shared hosting with moderate traffic to their site,
would you notice a significant performance downgrade if the site is
moved to heroku on 1 dyno?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] heruko performance vs shared hosting performance

2013-04-04 Thread John Merlino
This guy is using godaddy shared hosting for his wordpress blog. I
think it's currently $5 a month. I was thinking to use Rails for his
next project. But I wouldn't want costs to exceed more than $20 per
month. I contacted heroku and they said that 1 dyno is free to host
your ruby on rails app and each additional dyno is $30 a month. A
single Heroku dyno provides 512mb ram and 1024mb swap. It has 4
(virtual) CPU cores (Intel Xeon X5550 @ 2.67GHz). 512mb ram doesn't
seem to be much, particularly for memory-intensive processing.
Although, the multiple CPU cores may enhance multi-threading. That
said, this really isn't going to be a memory hog. Now I was curious to
compare these specs with that of a shared hosting environment (where
many different customers share the same resources). For example,
godaddy says this about their shared hosting Currently there is not a
‘set number’ for CPU resources. Mostly because we have multiple
hardware platforms in the wild. Simply put, if your processes degrade
performance for other customers on the server(s) we will take actions
to protect the other customers. So that's not much of a comparison.
But does anyone have any experience on shared hosting (I know that
most shared hosting environments dont support ruby - but Im sure you
used it for other platfroms like asp.net/php) vs heroku, and if
someone is used to shared hosting with moderate traffic to their site,
would you notice a significant performance downgrade if the site is
moved to heroku on 1 dyno?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] strange behavior with active relation any? method

2013-04-03 Thread John Merlino
In console, I run the following and any? returns true:
drivers = Driver.select(drivers.*,
drivers.id).joins([:reports, :driving_habits]).where(extract(MONTH
FROM reports.time) = ? AND extract(YEAR FROM reports.time) = ?, 3,
2013).uniq.order(drivers.id asc).page(2).per(1)
drivers.any?
 = true

This correctly evaluates to true because the relation contains one
returned record.

However, I run the same query within the Rails app itself, and any?
must evaluate @drivers in the view to either false or nil, because the
else is triggered instead when I click on second page in view. What's
even weirder is that when I call inspect on @drivers, then
@drivers.any? is evaluated to true in the view when I click on the
second page using kaminari:

@drivers = Driver.select(drivers.*, #{sort_column})
.joins([:reports, :driving_habits])
.by_month(for_selected_month.to_i,
for_selected_year.to_i)
.order(sort_column +   + sort_direction)
.page(params[:page]).per(1)

puts The drivers #{@drivers.inspect}


What's driving all this weird behavior?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] invoking helper method in controller and view breaks the separation of concern?

2013-04-02 Thread John Merlino
I came across some posts which postulate that it's undesirable to
share helper methods across controller and views because UI code
(designed to render HTML) should be separate from controller code
(designed for handling requests). That makes sense but there are
times, a good example is filtering, when it only makes sense to create
a reusable method to query against the params hash from both
controller and view. For example, I created some custom filtering and
sorting. When a http request is initially made, my controller must be
able to query the database for results without user input.


# controller layer (query a default without user input)
helper_method :sort_column, :sort_direction, :for_selected_month, 
:for_selected_year
def driver_reports_table
  @drivers = Driver.select(drivers.*,
#{sort_column}).joins([:reports, 
:driving_habits]).by_month(for_selected_month.to_i,
for_selected_year.to_i).order(sort_column +   +
sort_direction).page(params[:page]).per(10)
  @unit = current_unit
   respond_to do |format|
  format.html { render :partial = '/home/reports/
driver_reports_table', :layout = false, :locals = { :drivers =
@drivers, :unit = @unit } }
  format.json  { render :json = @drivers}
end
end


private

def sort_column
  if legal_attributes.include? params[:order]
params[:order]
  else
drivers.id
  end
end

def sort_direction
  %w[asc desc].include?(params[:direction]) ? params[:direction] :
asc
end

def for_selected_month
  (params[:date]  params[:date][:month]) || Time.now.month
end

def for_selected_year
  (params[:date]  params[:date][:year]) || Time.now.year
end

def legal_attributes
  @columns ||= Driver.column_names + DrivingHabit.column_names
end

In my view layer, the user will interact with form elements and links
to modify the values of the params hash
In one situation, I have a form tag where the user will set the date
and date and month/year attributes of the params hash:
#view
= form_tag driver_reports_path, :method = 'get', :id =
'drivers_filter' do
  %fieldset.filter_tab
= select_month(Date.today)
= select_year(Date.today, :start_year = 2012, :end_year =
Time.now.year)
= submit_tag Filter Date
= render '/home/reports/driver_reports_table'

In another situation, I have links where the user will set the sort
and direction attributes of the params hash, depending on which link
they click:
#partial
= hidden_field_tag :sort, params[:sort]
= hidden_field_tag :direction, params[:direction]
...
%table.sortable
  %tr
= sortable id, :order = drivers.id

#helper
def sortable(column, query_string={})
title ||= column.titleize
query_string[:order] = query_string[:order] || column
css_class = 'driver_refresh'
css_class  (column ==
sort_column.gsub(driving_habits.,).gsub(drivers.,) ?  current
#{sort_direction} : )
query_string[:direction] = column ==
sort_column.gsub(driving_habits.,).gsub(drivers.,) 
sort_direction == asc ? desc : asc
query_string[:page] = nil

content_tag :th, link_to(title,
driver_reports_path(params.merge(query_string)), {:class =
css_class })
  end

Each of the situations compensate for the other. If the user selects
an option from the select tag and thus populates the date attributes,
when they click a link, it will merge the date attributes from the
form with the link attributes that were selected and thus send them
together to the server. Conversely, when the form is submitted,
because of the hidden field tags with the current value of the sort
and direction attributes stored in them, those attributes will be send
with the form attributes.

As you can see, my view helper makes use of the sort_column and
sort_direction methods to check the current values in the params hash
to determine how to render the links. So those methods have importance
both in the controller and view layer. So it would make sense to
define the methods once and reuse them in both layers. So what is
wrong with this technique and how else could it be done so as not to
violate the MVC structure and separation of concerns?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: storing values in session variable vs instance variable

2013-03-20 Thread John Merlino
instance variables are alive as long as the object instance is alive. My 
question then would be from one http request to the next does the same 
controller instance remain alive? If so, then there's no need for sessions 
at all. Right?

On Tuesday, March 19, 2013 12:23:44 PM UTC-4, Ruby-Forum.com User wrote:

 Norm Scherer wrote in post #1102294: 
  On 03/18/2013 10:37 AM, John Merlino wrote: 
  Is there a good practice when to use the session variable. Sometimes I 
  find myself using both the session variable and instance variable. For 
  example, I have a table that allows a user to select a date. I store 
  the date both in the session and in the instance variable. Should I 
  not bother to store it in session? In what situations should you use 
  the session variable? -- 
  The rails session persists across requests while instance variables do 
  not.  If you need something in a following request it (or a reference) 
  must be in the session.  If you do not need it later I always use an 
  instance variable. 

 I wouldn't say that this is precisely accurate. You could continue 
 passing a variable from one request to another, and to third, and so on. 

 Session variables are useful when you really need a value to persist for 
 the entire session. I would also say that it's good practice to use 
 session variable sparingly. Session variables are somewhat akin to 
 global variables in the sense that they represent globally accessible 
 shared state (at least within the context of the current session). 

 Session variables are also long lived, taking up memory as long as the 
 session is kept alive. Although in a Rails application sessions are torn 
 down and recreate upon every request, but that might even be worse than 
 just leaving them in memory between requests. 

 Another thing to keep in mind is that by default Rails uses a cookie 
 based session storage mechanism, which means sessions have a hard 4K 
 limit (cookies are limited to 4K by spec). Another reason to avoid 
 putting large amounts of data in the session. 

 A typical use case for session variable are things like the id of the 
 current user. Notice I said the id not the user object itself. It's 
 better to load the user object when, and only when, necessary. There are 
 other great uses for session variables, but think twice about if it's 
 really necessary and try to keep the amount of data as small as 
 possible. Remember for every variable in the session is just one more 
 thing that has to be loaded from persistent storage on every single 
 request. 

 -- 
 Posted via http://www.ruby-forum.com/. 


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/WjlpqhZwf88J.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] using multiple joins in queries

2013-03-20 Thread John Merlino
I have this query:

Report.
joins(:alerts).
joins(:alert_code).
where(:unit_id = unit_id).
where{time  my{self.time}}.
where(alert_codes.name LIKE ?, %Inside virtual
fence%).
order(reports.time DESC).first

Basically, it breaks:

ActiveRecord::ConfigurationError (Association named 'alert_code' was
not found; perhaps you misspelled it?):


My associations look like this:

report has_many alerts
alert belongs_to :alert_code, :foreign_key = :code

I am trying to get the first report whose alerts belongs to alert_code
whose name is inside virtual fence. So there are 3 associations
here. Trying to establish the connection.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] storing values in session variable vs instance variable

2013-03-18 Thread John Merlino
Is there a good practice when to use the session variable. Sometimes I find 
myself using both the session variable and instance variable. For example, 
I have a table that allows a user to select a date. I store the date both 
in the session and in the instance variable. Should I not bother to store 
it in session? In what situations should you use the session variable?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/wT4_mu7jFkMJ.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] render and render_to_string

2013-03-18 Thread John Merlino
render_to_string  returns the result of executing some template or
partial in a string instead of sending it as the response body to the
browser. Render returns the result of evaluating some template or
partial as a string of html, like render_to_string, but it then sends
it back as part of the response body to the browser. Now with ajax,
when I use jquery's get method like this:

$.get(url, function(resp) {
  $('#tabs').append(resp);
})


If I use render_to_string, it sends an actual string back the browser
and thats what is appended to the DOM. When I use render, it returns
HTML back to the browser and thats what is correctly appended to the
DOM.

So what causes the difference? Does render send as part of the
response body a header like text/html or something?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] check how long individual active record queries take to the database

2013-03-15 Thread John Merlino
I know that Rails output log shows how many milliseconds a sql query
take but I'm looking for something more fine-tuned. I want to know how
long individual activerecord queries take on an indiivdual basis. For
example, I have code that looks like this:

items = current_user.accessible_items
@items = items.where{item_id ==
my{current_user.item_id}}.ordered
@other_items = current_user.accessible_items.where{item_id !=
my{current_user.item_id}}.ordered
@accounts = @other_items.accounts.ordered

There are several database hits here. How can I check how long they
take?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: evaluating expressions left to right

2012-12-27 Thread John Merlino
That was my hunch. Thanks for clarifying.

On Wednesday, December 26, 2012 6:48:18 PM UTC-5, Matt Jones wrote:



 On Tuesday, 25 December 2012 20:13:16 UTC-5, John Merlino wrote:

 ok, it didn't look like nested methods. But I made to believe that 
 this: 

 sum=square*deviation|a 

 is exactly the same as this: 

 sum=(square*(deviation|(a))) 

 So if this is true, then still a question remains. 


  That's not how it parses, thanks to operator precedence - the same reason 
 that 2+5*10+3 parses as 2.+((5.*(10)).+(3)) and not 2.+(5.*(10.+(3))).

  You can use a tool like Ripper (
 http://www.rubyinside.com/using-ripper-to-see-how-ruby-is-parsing-your-code-5270.html)
  
 to see exactly how something is being parsed. Trying your expression yields:

 [:program,
  [[:binary,
[:vcall, [:@ident, sum, [1, 0]]],
:=,
[:binary,
 [:binary,
  [:vcall, [:@ident, square, [1, 5]]],
  :*,
  [:vcall, [:@ident, deviation, [1, 12,
 :|,
 [:vcall, [:@ident, a, [1, 22]]]

 Or, distilled back to a fully-parenthized code version:

 sum = ((square*deviation) | a)

 With the method calls written out explicitly:

 sum.=((square.*(deviation)).|(a))

 Essentially, this creates a function that calculates the squared deviation 
 from the mean (square*deviation), applies it to the list a, and then sums 
 the resulting values.

 This sort of confusion is why most people recommend avoiding operator 
 overloading in most cases - there are a bunch of precedence rules built 
 into the language, and you're essentially stuck with them.

 --Matt Jones


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/Td1UvO4YivgJ.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: evaluating expressions left to right

2012-12-25 Thread John Merlino
ok, it didn't look like nested methods. But I made to believe that
this:

sum=square*deviation|a

is exactly the same as this:

sum=(square*(deviation|(a)))

So if this is true, then still a question remains.

Here's the original context again:


module Functional

  def compose(f)
if self.respond_to?(:arity)  self.arity == 1
  lambda { |*args| self[f[*args]] }
else
  lambda {|*args| self[*f[*args]] }
end
  end
  alias * compose


  def apply(enum)
enum.map self
  end
  alias | apply

  def reduce(enum)
enum.inject self
  end
  alias = reduce

end

class Proc
  include Functional
end

#client code
a = [1,2,3]
sum = lambda { |x,y| x+y }
mean = (sum=a)/a.size
deviation = lambda { |x| x-mean }
square = lambda { |x| x*x }
standardDeviation = Math.sqrt((sum=square*deviation|a)/(a.size-1))

On the last line, this executes first:

deviation|a

this returns a new array of how far each of elements are from the
mean.

Then this array gets passed to * which is invoked on square (a lambda
object):

square*returned_array

That calls compose where f parameter is the returned array from above.
So then this line is returned by compose since the array object doesnt
respond to arity:

lambda {|*args| self[*f[*args]] }

So it appears the return value of compose is the lambda object. That
presents a problem because = expects an enum argument.

sum=this_should_be_an_enum


On Dec 23, 3:14 am, 7stud -- li...@ruby-forum.com wrote:
 In this method call:

 meth1(meth2(meth3))

 ...which value has has to be computed first so that meth1 can return?

 --
 Posted viahttp://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] passing lambda when expecting an enumerable

2012-12-22 Thread John Merlino
Here are two methods defined in the Proc class, designed to be used
for functional programming:

  def apply(enum)
enum.map self
  end
  alias | apply

  def reduce(enum)
enum.inject self
  end
  alias = reduce


Here's an application of them:

sum = lambda {|x,y| x+y }
mean = (sum=a)/a.size
deviation = lambda {|x| x-mean }
square = lambda {|x| x*x }
standardDeviation = Math.sqrt((sum=square|(deviation|a))/(a.size-1))

This excerpt is taken from The Ruby Programming Language.

Here's the thing. In the last line of the above code it uses
sum=square. That reduce method expects an enumerable as an
argument. And instead it is being sent a lambda held in square
variable. This should fail because the inject method does not exist on
the lambda. It exists on arrays, and other enumerable types. So what
am I missing here?






-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: passing lambda when expecting an enumerable

2012-12-22 Thread John Merlino
ok I see what it;s doing. Its first calculating this part:

(deviation|a)

to check how far the elements deviate from the mean and returns an
array of the differences.

Then what happens next is that the square| is invoked on the returned
array from above:

square|deviation_returned_array

So it squares the result set, which returns an array of the
deviation_returned_array squared. THen we invoke reduce passing
squared_deviation_returned_array enumerable to the sum proc, which
just totals the result set:

sum=squared_deviation_returned_array

And then divide by (a.size-1) and take the square root of it.


So I guess the lesson here is not only do parentheses indicate
priority in evaluating an expression, but the expressions next to the
ones in parentheses are evaluated before starting to evaluate from
left to right.





On Dec 22, 10:10 am, John Merlino stoici...@aol.com wrote:
 Here are two methods defined in the Proc class, designed to be used
 for functional programming:

   def apply(enum)
     enum.map self
   end
   alias | apply

   def reduce(enum)
     enum.inject self
   end
   alias = reduce

 Here's an application of them:

 sum = lambda {|x,y| x+y }
 mean = (sum=a)/a.size
 deviation = lambda {|x| x-mean }
 square = lambda {|x| x*x }
 standardDeviation = Math.sqrt((sum=square|(deviation|a))/(a.size-1))

 This excerpt is taken from The Ruby Programming Language.

 Here's the thing. In the last line of the above code it uses
 sum=square. That reduce method expects an enumerable as an
 argument. And instead it is being sent a lambda held in square
 variable. This should fail because the inject method does not exist on
 the lambda. It exists on arrays, and other enumerable types. So what
 am I missing here?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] evaluating expressions left to right

2012-12-22 Thread John Merlino
class Proc
def apply(enum)
enum.map self
  end
  alias | apply

  def reduce(enum)
enum.inject self
  end
  alias = reduce

def compose(f)
if self.respond_to?(:arity)  self.arity == 1
  lambda {|*args| self[f[*args]] }
else
  lambda {|*args| self[*f[*args]] }
end
  end
  alias * compose

end

sum = lambda {|x,y| x+y }# A function to add two numbers
mean = (sum=a)/a.size   # Or sum.reduce(a) or a.inject(sum)
deviation = lambda {|x| x-mean } # Function to compute difference from
mean
square = lambda {|x| x*x }   # Function to square a number
standardDeviation = Math.sqrt((sum=square*deviation|a)/(a.size-1))

Ok so now I have another example from this book which does not contain
parentheses around deviation|a. So then why is this part:

(sum=square*deviation|a)

not evaluated from left to right.

Apparently, it evaluates this part:

deviation|a

first

and this part second:

square*deviation|a

and then finally:

sum=

So it looks like it is evaluating from right to left. Even though it
should be evaluating from left to right...



-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] reading bytes and blocking

2012-10-30 Thread John Merlino
I come across this method:

read(n=nil, buffer=nil) – read n bytes (or fewer, if EOF is reached),
blocking if necessary, until the bytes are ready.

What does it mean blocking if necessary? Blocking what?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] why is thread asleep?

2012-10-25 Thread John Merlino
In this example:

1.9.3p0 :001  def threading
1.9.3p0 :002?   i = 0
1.9.3p0 :003?   while i = 50
1.9.3p0 :004? sleep(2)
1.9.3p0 :005? i += 1
1.9.3p0 :006? if i == 50
1.9.3p0 :007?   puts the thread is finished at #{Time.now}
1.9.3p0 :008?   end
1.9.3p0 :009? end
1.9.3p0 :010?   end
 = nil
1.9.3p0 :011  t = Thread.new { threading }
 = #Thread:0x007f833d301660 sleep
1.9.3p0 :012  t.status
 = sleep
1.9.3p0 :013  t.stop?
 = true
1.9.3p0 :014  t.alive?
 = true
#few minutes later:
1.9.3p0 :015  the thread is finished at 2012-10-25 21:52:43 -0400

As soon as threading is invoked in the new thread, I check its status.
And the status is sleep. Why is it sleep and not runnable?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: why is thread asleep?

2012-10-25 Thread John Merlino
Oh I see, because of the call to Kernel.sleep forces the thread in a
sleeping state.

On Oct 25, 9:55 pm, John Merlino stoici...@aol.com wrote:
 In this example:

 1.9.3p0 :001  def threading
 1.9.3p0 :002?   i = 0
 1.9.3p0 :003?   while i = 50
 1.9.3p0 :004?     sleep(2)
 1.9.3p0 :005?     i += 1
 1.9.3p0 :006?     if i == 50
 1.9.3p0 :007?       puts the thread is finished at #{Time.now}
 1.9.3p0 :008?       end
 1.9.3p0 :009?     end
 1.9.3p0 :010?   end
  = nil
 1.9.3p0 :011  t = Thread.new { threading }
  = #Thread:0x007f833d301660 sleep
 1.9.3p0 :012  t.status
  = sleep
 1.9.3p0 :013  t.stop?
  = true
 1.9.3p0 :014  t.alive?
  = true
 #few minutes later:
 1.9.3p0 :015  the thread is finished at 2012-10-25 21:52:43 -0400

 As soon as threading is invoked in the new thread, I check its status.
 And the status is sleep. Why is it sleep and not runnable?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] limitations of passing a block to class_eval

2012-10-19 Thread John Merlino
One shortcoming of define_method is that it does not allow you to
specify a method body that expects a block. If you need to dynamically
create a method that accepts a block, you will need to use the def
statement within class_eval. Here's a trivial example:

class Module
  def acts_as_thing(name, block)
self.class_eval {
  define_method(name, block)
}
  end
end

class Thing
  #using define_method does not allow us to specify a method body that
expects a block, because the block used in define method becomes the
method body itself, not a block passed to a method body.
  acts_as_thing :animals do
puts animal group
  end

  def initialize(name)
@name = name
  end
end

#To address the limitations of define_method, that is, to dynamically
create a method that accepts a block, we need to use the def statement
with class_eval.
Thing.class_eval {
  def spell_out_name
yield @name
  end
}

thing = Thing.new(dog)
thing.animals # = animal group
thing.spell_out_name {|name| puts The name is #{name}.} # = The
name is dog.

Here's my question. I am reading a book called The Ruby Programming
Language. It says the following:

If the method you are creating is sufficiently dynamic, you may not
be able to pass a block to class_eval and will instead have to specify
the method definition as a string to be evaluated.

I'm not sure what they are talking about here. What does it mean by
sufficiently dynamic? In my example above, I proved that a method
defined within the context of class_eval can accept a block.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Why does Kernel define class_eval?

2012-10-13 Thread John Merlino
First, I'd like to say it makes sense to define instance_eval in
BasicObject. Both object instances (e.g. obj = Object.new or obj =
MyClass.new) and class objects (e.g. MyClass = Class.new) are both
instances of a class, in the former of the class Object or a client-
defined class (which implicitly inherits from Object) and in the
latter of the class Class. But because they are both instances, we
want to give them both access to the method instance_eval. It makes
sense to define this method instance_eval in either Object or
BasicObject, so that they will be inherited by regular object
instances and class objects.

class_eval is justifiably declared in the Module class. class_eval
evaluates a class and adds instance methods to that class. All class
objects are instances of Class, and Module is the superclass of Class.
Hence, all class objects have access to the instance methods of
Module, where class_eval is defined, in addition to them having access
to the instance methods of class Class. For example:

1.9.3p0 :092  MyClass.class_eval {
1.9.3p0 :093  def my_class
1.9.3p0 :094? puts yes im an instance method of
#{self.class.name}
1.9.3p0 :095? end
1.9.3p0 :096?   }
 = nil
1.9.3p0 :097  MyClass.new.my_class
yes im an instance method of MyClass

Basically, what we did with class_eval is evaluate the class context
to add methods to it for the class' instances. So it really would not
make sense to have a class_eval definition available to instances
themselves. Yet, in the current library, it's possible:

1.9.3p0 :098  obj = Object.new
 = #Object:0x007ff4ec8fc0f8
1.9.3p0 :099  obj.class_eval {}
 = nil

What's written above really doesn't make any sense, but it works.
There's no NoMethodError exception raised when invoking class_eval on
the object instance. In actuality, that class_eval invocation does not
trace to Module's definition of class_eval. That would be impossible,
because obj is an instance of Object class, which inherits from
BasicObject and the inheritance chain stops there. There's no Module
in obj's inheritance chain. So then where is class_eval defined for
obj? It's defined in Kernel:

1.9.3p0 :083  Kernel.instance_methods(false).include? :class_eval
 = true

As you may know, the Kernel module is included in Object and hence all
its method definitions become available as instance methods to Object,
so that when our obj instance invokes class_eval, it will first search
Object class, and then check the module Kernel, where the definition
will be found.

But I don't see why class_eval is defined in Object. The obj instance
is not a class object, and therefore the new method is not available
to it, so it's not like we can add instance methods to obj within the
block of class_eval:

1.9.3p0 :098  obj = Object.new
 = #Object:0x007ff4ec8fc0f8
1.9.3p0 :101  obj.class_eval {
1.9.3p0 :102  def my_class
1.9.3p0 :103? puts yes im an instance method of
#{self.class.name}
1.9.3p0 :104? end
1.9.3p0 :105?   }
 = nil
1.9.3p0 :106  obj.new.my_class
NoMethodError: undefined method `new' for #Object:0x007ff4ec8fc0f8

#as expected, the exception is raised, because obj is not a class
object.

So why is class_eval in Kernel? obj is not a class object, and we
shouldn't be allowed to invoke class_eval on obj...

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] What is the best way to check if a method is a singleton method or an instance method?

2012-10-12 Thread John Merlino
Let's say I want to check if a method of an object is an instance
method or a singleton method, what is the best way to do it?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] IRB vs ruby-doc.org

2012-10-12 Thread John Merlino
The ruby documentation says instance_variable_set is a public instance
method of Object:

http://ruby-doc.org/core-1.9.3/Object.html#method-i-instance_variable_set

And I believe it because you can call it on instances of Object:

1.9.3p0 :005  Object.new.instance_variable_set :@a, 1
 = 1

It can't be a public instance method of Class or Module, because
otherwise the Object instance wouldnt have access to it, since the
above Object instance is an instance of Object, whose superclass is
BasicObject and that's it.

So my question is why when I launch IRB in Rails 3/Ruby 1.9.3, and
return as an array the instance methods of Object,
instance_variable_set is no where to be found:

1.9.3p0 :001  Object.instance_methods(false)
 =
[:psych_to_yaml, :to_yaml_properties, :to_yaml, :in?, :blank?, :present?, 
:presence, :acts_like?, :try, :html_safe?, :duplicable?, :to_param, :to_query, 
:`, :instance_values, :instance_variable_names, :to_json, :with_options, 
:as_json]

Shouldn't instance_variable_set be listed here?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] marshal vs yaml

2012-10-09 Thread John Merlino
I notice how Rails makes heavy use of YAML serialization, but a lot of the 
Ruby literature I come across places emphasis on Marshal. One powerful 
technique with marshal is the marshal_dump and marshal_load hooks used to 
customize storing and retrieving object states. For example, let's say I 
have an object that can store as instance variables an arbitrary array of 
integers. And let's say I simply want to marshal that array rather than the 
whole object state, and then later retrieve that data and store it into an 
allocated but unitialized new instance of the object. Then the marshal_dump 
and marshal_load hooks come in handy:

class Point
  def initialize(*coords)
@coords = coords
  end

  def marshal_dump
@coords.pack(w*)
  end

  def marshal_load(s)
@coords = s.unpack(w*)
  end
end

Is there a more effective way to achieve something like this in YAML that 
the Rails community prefers?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msg/rubyonrails-talk/-/GZdvmxERMyYJ.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] dup/clone and taintedness

2012-10-07 Thread John Merlino
I was reading this:

these methods allocate a new instance of the class of the object on
which they are invoked. They then copy all the instance variables and
the taintedness of the receiver object to the newly allocated object.

What does it mean taintedness?

thanks for response

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] TypeError: can't make subclass of Class

2012-10-06 Thread John Merlino
Why can't a class be an instance of class Class and also inherit from
class Class in ruby?


Let's say I defined a singleton method on Class:

1.9.3p0 :032  class Class
1.9.3p0 :033?   def Class.class_singleton
1.9.3p0 :034? puts 'class singleton'
1.9.3p0 :035? end
1.9.3p0 :036?   end

And I want to create a class that can inherit that singleton method:

1.9.3p0 :039  class Q  Class
1.9.3p0 :040?   end
TypeError: can't make subclass of Class

How then could it be possible to access that singleton method without
directly calling it on Class? And why is inheriting from Class not
allowed?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] more misleading content on the web regarding ruby method lookup algorithm

2012-10-06 Thread John Merlino
I read this article:

http://www.madebydna.com/all/code/2011/06/24/eigenclasses-demystified.html

Author makes claim that are flat out wrong. She says: Class gets
pushed up the lookup chain and becomes a superclass. That statement
is flat out wrong. A class object does not inherit from class Class.
In fact, if you try it you will get a TypeError. A class object is an
instance of class Class. If a class object does not inherit from
anything, then it implicitly inherits from class Object, which itself
is an instance of class Class. What happens is as follows: First off,
when a class (aka singleton) method is defined on class Dog, an
eigenclass is created. For all intents and purposes, this eigenclass
becomes the class of the Dog object. Class does not get pushed up
the lookup chain. It's the superclass that gets pushed up the lookup
chain, which in this example, is Mammal. In other words, it will look
at Dog's eigenclass and if it doesn't find it there, it will then look
at Mammal's eigenclass, and then Object (so its Object that
continuously gets pushed back) and then BasicObject. Here's an example
that shows Class does not get pushed back, because the class object
never even inherits the eigenclass of Class to begin with (the class
object is simply an instance of Class):


Loading development environment (Rails 3.1.2)
1.9.3p0 :001  class Mammal
1.9.3p0 :002? def Mammal.mammal_singleton
1.9.3p0 :003? puts 'mammal singleton'
1.9.3p0 :004?   end
1.9.3p0 :005?   end
 = nil
1.9.3p0 :006 
1.9.3p0 :007class Dog  Mammal
1.9.3p0 :008? def Dog.dog_singleton
1.9.3p0 :009? puts 'dog singleton'
1.9.3p0 :010?   end
1.9.3p0 :011?   end
 = nil
1.9.3p0 :012 
1.9.3p0 :013class Object
1.9.3p0 :014? def Object.object_singleton
1.9.3p0 :015? puts 'object singleton'
1.9.3p0 :016?   end
1.9.3p0 :017?   end
 = nil
1.9.3p0 :018 
1.9.3p0 :019class Class
1.9.3p0 :020? def Class.class_singleton
1.9.3p0 :021? puts 'class singleton'
1.9.3p0 :022?   end
1.9.3p0 :023?   end
 = nil
1.9.3p0 :024  Dog.dog_singleton
dog singleton
 = nil
1.9.3p0 :025  Dog.mammal_singleton
mammal singleton
 = nil
1.9.3p0 :026  Dog.object_singleton
object singleton
 = nil
1.9.3p0 :027  Dog.class_singleton
NoMethodError: undefined method `class_singleton' for Dog:Class
from (irb):27

#It fails because class Class is not in the eigenclass lookup chain of
Dog class object, since class Class is not a superclass of Dog.
However, by defining an instance method in class Class, then that will
be able to be invoked on Dog, since Dog is an instance of class Class:

1.9.3p0 :028  class Class
1.9.3p0 :029?   def class_instance
1.9.3p0 :030? puts 'class instance'
1.9.3p0 :031? end
1.9.3p0 :032?   end
 = nil
1.9.3p0 :033  Dog.class_instance
class instance
 = nil

So the real question is this, which that article obscured. If I invoke
a method on Dog, will it search the Class hierarchy for an associated
instance method first (and continue looking up the lookup algorithm
for instance methods via Module, Object, and BasicObject which class
Class inherits from) or will it search Dog's eigenclass and its
superclasses' eigenclasses (all the way up to the eigenclass of Object
and BasicObject) first? The proof is in the pudding:

1.9.3p0 :044  class Object
1.9.3p0 :045?   def Object.sing_method
1.9.3p0 :046? puts 'singleton method'
1.9.3p0 :047? end
1.9.3p0 :048?   def inst_method
1.9.3p0 :049? puts 'instance method'
1.9.3p0 :050? end
1.9.3p0 :051?   end
 = nil
1.9.3p0 :052  Dog.sing_method
singleton method
 = nil
1.9.3p0 :053  Dog.inst_method
instance method
 = nil
#as suspected, invocations on Dog lead to both eigenclass methods of
Object and instance methods of Object, since Dog is an instance of
class Class, and class Class inherits from Object via Module, and Dog
at the same time inherits from Object (via inheritance), which is done
implicitly by Ruby. Now which get invoked first, the instance methods
or eigenclass methods?

1.9.3p0 :062  class Object
1.9.3p0 :063?   def Object.method_lookup
1.9.3p0 :064? puts 'eigenclass method called first!'
1.9.3p0 :065? end
1.9.3p0 :066?   def method_lookup
1.9.3p0 :067? puts 'instance method is called first!'
1.9.3p0 :068? end
1.9.3p0 :069?   end
 = nil
1.9.3p0 :070  Dog.method_lookup
eigenclass method called first!
 = nil

And there you have it, the method resolution algorithm looks up the
singleton methods prior to the instance methods of a class object.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] protected method access

2012-10-03 Thread John Merlino
I just want to make a note of something I read here:

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Protected

def =(other)
self.age = other.age
  end

It says:

If age is private, this method will not work, because other.age is
not accessible. If age is protected, this will work fine, because
self and other are of same class, and can access each other's
protected methods.

That statement is not actually true. They won't access each other's
protected methods. They will access their own protected methods of the
same class.

Demonstration:

1.9.3p0 :001  class A
1.9.3p0 :002?   protected
1.9.3p0 :003?   def method
1.9.3p0 :004? puts self is #{self.object_id}
1.9.3p0 :005? end
1.9.3p0 :006?   end

1.9.3p0 :009  class A
1.9.3p0 :010?   def calling_method(o)
1.9.3p0 :011? self.method
1.9.3p0 :012? o.method
1.9.3p0 :013? end
1.9.3p0 :014?   end
 = nil
1.9.3p0 :015  b = A.new
 = #A:0x007fcfe5b20900
1.9.3p0 :016  a.calling_method(b)
self is 70265443297880
self is 70265444304000

As you can see, b is not invoking a's protected method. It's invoking
its own, that was stored separately in this object, just as the
instance vars are stored separately per object. I'm sure that's what
the book intended, but when it comes to writing, you have to be
careful to clarify for accuracy.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: Class, Module, Object

2012-10-03 Thread John Merlino
, 
:pretty_print_cycle, :pretty_print, :xyz]
1.9.3p0 :099  Object.included_modules
 = [PP::ObjectMixin, ActiveSupport::Dependencies::Loadable,
JSON::Ext::Generator::GeneratorMethods::Object, Kernel]

And there you go, it worked.


On Sep 22, 8:09 pm, Ignacio Piantanida ijpiantan...@gmail.com wrote:
 Class, Module and Object are instances of the Class class. Class.class
 = Class
  Module.class
 = Class
  Object.class

 = Class

 Class inherits from Module, which inherits from Object Class.superclass
 = Module
  Module.superclass

 = Object

 So, every instance of the Class class is_a?(Class) and is_a?(Module) and
 is_a?(Object).

 2012/9/22 John Merlino stoici...@aol.com







   reload!
  Reloading...
  = true
   puts Class  Module
  true
  = nil
   puts Module  Class
  false
  = nil
   puts Module  Object
  true
  = nil
   puts Object  Module
  false
  = nil
   Object.parent
  = Object

  The above indicates that the Class object instance inherits from the
  Module object instance and the Module object instance inherits from
  Object. And Object doesn't inherit from anything.

  So why do these return true:

   Module.is_a?(Class)
  = true
   Object.is_a?(Module)
  = true

  --
  You received this message because you are subscribed to the Google Groups
  Ruby on Rails: Talk group.
  To post to this group, send email to rubyonrails-talk@googlegroups.com.
  To unsubscribe from this group, send email to
  rubyonrails-talk+unsubscr...@googlegroups.com.
  For more options, visithttps://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: Class, Module, Object

2012-10-03 Thread John Merlino
I want to fix a typo. I said:

Since Object, Class, and Module are instances of Class class, they
don't have access to Class's singleton methods, but rather they have
access to Class's instance methods:

I meant to say:

Object and Module do not inherit from Class and so they
don't have access to Class's singleton methods, but since Object,
Class, and Module are instances of Class class, they all have
access to Class's instance methods:

On Oct 3, 11:08 pm, John Merlino stoici...@aol.com wrote:
 Yes, Object, Class, and Module are more than just constants.  Object,
 Class, and Module are instances of Class class:

 1.9.3p0 :031  Class.class
  = Class
 1.9.3p0 :032  Module.class
  = Class
 1.9.3p0 :033  Object.class
  = Class

 Since Object, Class, and Module are instances of Class class, they
 don't have access to Class's singleton methods, but rather they have
 access to Class's instance methods:

 1.9.3p0 :052  class Class
 1.9.3p0 :053?   def Class.abc
 1.9.3p0 :054?     puts 'abc'
 1.9.3p0 :055?     end
 1.9.3p0 :056?   end
  = nil

 1.9.3p0 :076  Module.abc
 NoMethodError: undefined method `abc' for Module:Class

 1.9.3p0 :077  Object.abc
 NoMethodError: undefined method `abc' for Object:Class

 However, since we defined the singleton method on Class, it will work
 on a Class invocation:

 1.9.3p0 :078  Class.abc
 abc
  = nil

 But instance methods work:

 1.9.3p0 :012  Class.instance_methods(false)
  =
 [:allocate, :new, :superclass, :cattr_reader, :cattr_writer, :cattr_accessor,
 …]

 1.9.3p0 :015  Object.cattr_writer
  = []
 1.9.3p0 :017  Module.cattr_reader
  = []
 1.9.3p0 :018  Class.cattr_writer
  = []

 This here is an indication that Object and Module are instances of
 Class but DO NOT inherit from Class. Let's check that out with the
 superclass call:

 1.9.3p0 :079  Class.superclass
  = Module
 1.9.3p0 :080  Module.superclass
  = Object
 1.9.3p0 :081  Object.superclass
  = BasicObject
 1.9.3p0 :082  BasicObect.superclass
  = nil

  Thus, Class inherits from Module, and Module in turn inherits from
 Object, which in turn inherits from BasicObject in ruby 1.9. We can
 test that out by seeing if we define a singleton method on Module,
 then Class should be able to invoke it, since there is inheritance
 between them.

 1.9.3p0 :067  class Module
 1.9.3p0 :068?   def Module.qqqw
 1.9.3p0 :069?     puts 'qqqw'
 1.9.3p0 :070?     end
 1.9.3p0 :071?   end
  = nil
 1.9.3p0 :072  Module.singleton_methods(false)
  =
 [:nesting, :constants, :attr_internal_naming_format, 
 :attr_internal_naming_format=, :qqqw]
 1.9.3p0 :073  Class.qqqw
 qqqw
  = nil
 1.9.3p0 :074  Object.qqqw
 NoMethodError: undefined method `qqqw' for Object:Class

 1.9.3p0 :084  class Object
 1.9.3p0 :085?   def Object.ttyy
 1.9.3p0 :086?     puts 'ttyy'
 1.9.3p0 :087?     end
 1.9.3p0 :088?   end
  = nil
 1.9.3p0 :089  Module.ttyy
 ttyy
  = nil
 1.9.3p0 :090  Class.ttyy
 ttyy
  = nil

 This shows the role of inheritance. We defined a singleton method on
 Object, and thus since Module inherits from Object, it had access to
 it, and so did Class, since Class inherits from Module, which in turn
 inherits from Object.

 Now that's the metaclass (eigenclass) inheritance relationship (the
 fact that the eighenclass of Class inherits the singleton methods of
 the eighenclass of Module which in turn inherits the singleton methods
 of eigenclass of Object). If the inheritance relationship did not
 exist as it does, then we wouldnt be able to call singleton methods of
 Module on Class, for example.

 Furthermore, we have a circular relationship. Since Class is an
 instance of Class, Module is an instance of Class, and Object is an
 instance of Class, they all have access to instance methods of Class,
 as already stated. What's more interesting is the circular
 relationship that has been created via the combination of
 instantiation and inheritance. If Object is an instance of Class, and
 Class inherits from Module, then that means Class is an instance of
 Module, and so since Object is an instance of Class, it itself is an
 instance of Module. Hence, we can access the INSTANCE METHODS of any
 of these classes via the other Class.

 1.9.3p0 :094  Class.is_a?(Module)
  = true
 1.9.3p0 :095  Module.is_a?(Class)
  = true
 1.9.3p0 :096  Object.is_a?(Module)
  = true
 1.9.3p0 :097  Object.is_a?(Class)
  = true

 Now lets access an instance method of Module on Object:

 1.9.3p0 :098  Module.instance_methods(false)
  =
 [:freeze, :===, :==, :=, :, :=, :, :=, :to_s, :included_modules, 
 :include?, :name, :ancestors, :instance_methods, :public_instance_methods, 
 :protected_instance_methods, :private_instance_methods, :constants, 
 :const_get, :const_set, :const_defined?, :class_variables, 
 :remove_class_variable, :class_variable_get, :class_variable_set, 
 :class_variable_defined?, :public_constant, :private_constant, :module_exec, 
 :class_exec, :module_eval, :class_eval, :method_defined?, 
 :public_method_defined?, :private_method_defined

[Rails] Re: global methods under object supposedly unaccessible

2012-10-02 Thread John Merlino
A private method is internal to the implementation of a class, and it
can only be called by other instance methods of the class (or its
subclasses). Private methods are implicitly invoked on self, and may
not be explicitly invoked on an object. If m is a private method, then
you must ibnvoke it in functional style as m.

But look at this:

1.9.3p0 :032  class Object
1.9.3p0 :033?   def apple2
1.9.3p0 :034? puts 'apple2'
1.9.3p0 :035? end
1.9.3p0 :036?   end
 = nil
1.9.3p0 :037  self.apple2
apple2
 = nil

Or this:

1.9.3p0 :038  def apple2
1.9.3p0 :039?   puts 'apple2'
1.9.3p0 :040?   end
 = nil
1.9.3p0 :041  self.apple2
apple2
 = nil


I invoked apple2 on self (an explicit receiver). However, according to
documentation, defining apple2 in Object should have made it private.

Only this would work:

1.9.3p0 :025  class Object
1.9.3p0 :026?   private
1.9.3p0 :027?   def apple1
1.9.3p0 :028? puts 'apple1'
1.9.3p0 :029? end
1.9.3p0 :030?   end
 = nil
1.9.3p0 :031  self.apple1
NoMethodError: private method `apple1' called for main:Object

However, in the above example, I was forced to use the private method.
The documentation says any global methods declared outside of a class
definition - those methods are defined as private instance methods of
Object.
In my first examples, I defined a method outside of class definition.
But was still able to invoke it on self (self being Object in that
case).

On Sep 23, 7:16 pm, 7stud -- li...@ruby-forum.com wrote:
 1) Post the definition ofprivate.

 2) Execute this program:

 puts 'hello'

 3) What conclusions do you draw from that?

 --
 Posted viahttp://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] struct square brackets method used to instantiate?

2012-10-01 Thread John Merlino
I know that Struct class defines the [] instance method:

1.9.3p0 :014  Struct.instance_methods(false)
 =
[:==, :eql?, :hash, :inspect, :to_s, :to_a, :values, :size, :length, :each, 
:each_pair, :
[], :
[]=, :select, :values_at, :members, :pretty_print, :pretty_print_cycle, 
:as_json]

This allows you to mimic hash behavior via Struct:

1.9.3p0 :016  HashLike = Struct.new(:x,:y)
 = HashLike
1.9.3p0 :017  h = HashLike.new(1,2)
 = #struct HashLike x=1, y=2
1.9.3p0 :018  h[:x]
 = 1
1.9.3p0 :019  h[:y] = 100
 = 100

But I come across a use case where the square brackets method was used
as instantiation:

1.9.3p0 :001  Point = Struct.new :x, :y do
1.9.3p0 :002  def distance(point)
1.9.3p0 :003? Math.sqrt((point.x - self.x) ** 2 +
1.9.3p0 :004  (point.y - self.y) ** 2)
1.9.3p0 :005? end
1.9.3p0 :006?   end
 = Point
1.9.3p0 :007  Point[3,4].distance Point[0,0]
 = 5.0

That confuses me. How can [] be used both as both hash key accessors
and also instantiation (e.g. new)?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: in Rails, what is the main (global) scope called?

2012-09-26 Thread John Merlino
Top-level methods or constants defined outside of any class or module
are implicitly defined in Object.

On Sep 21, 1:30 pm, John Merlino stoici...@aol.com wrote:
 For example, you see filescalled

 rails/actionpack/lib/action_controller/base.rb

 which adds methods and such to the open module ActionController. Whatscopeis 
 ActionController in? Is it justcalledtheglobalscope?
 Obviously, there is namespace resolution lookup. And a good example of
 this is in the Base class of the same file. It references one module
 like this: AbstractController::Layouts  and another module like this:
 Rendering. One uses the :: namespace resolution operator, because
 Layouts module is not within thescopethat class Base is, which is
 module ActionControllerscope, so it has to reference
 AbstractController which must be in theGLOBALscopein order for ruby
 to find it and then it can look there to find Layouts. In contrast,
 Rendering is defined within the ActionControllerscope, and since
 class Base is defined within the ActionControllerscopeas well, it
 doesn't need to use the :: operator. It can simply search within thatscopeand 
 find the module Rendering. So what is thatglobalscopethat
 ActionController and AbstractController are in withinRails?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] How is the Kernel module an ancestor of Object?

2012-09-26 Thread John Merlino
inheritance chain:

Class - Module - Object

Kernel.is_a?(Module) # = true

Kernel is an instance of Module, which in turn inherits from Object.

So how is Kernel an ancestor of Object?

I found it on line 262 of The Ruby Programming Language:

The Kernel module is an ancestor of Object.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] method name resolution

2012-09-25 Thread John Merlino
For the method invocation expression o.m, Ruby performs name
resolution with the following steps: 1) first, it checks the
eigenclass of o for singleton methods named m. 2) If no method m is
found in the eigenclass, Ruby searches the class of the o for an
instance method named m. 3) If no method m is found in the class, Ruby
searches the instance methods of any modules included by the class of
o. If that class includes more than one module, then they are searched
in the reveerse of the order in which they wre included. That is, the
most recently included module is searched first. If no instance method
m is found in the class of o or in its modules, then the search moves
up the inheirtance hierarchy to the superclass. Steps 2 and 3 are
repeated for each class in the inheritance heirarchy until each
ancestor class and its included modules have been searched. If no
method named m is found after completing the search, then a method
named method_missing is invoked instead. In order to find an
appropriate definition of this method, the name resolution algorithm
starts over at step 1. The kernel module provides a default
implementation of method_missing, so this second pass of name
resolution is guaranteed to succeed.

Notice the part Steps 2 and 3 are repeated for each class in the
inheritance heirarchy...

What if the superclass has an eigenclass method? Why doesn't it repeat
Step 1?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: method name resolution

2012-09-25 Thread John Merlino
The answer is that when Ruby searches for singleton methods in the
eigenclass of an object, it also searches the superclass (and all
ancestors) of the eigenclass as well.

On Sep 25, 11:05 pm, John Merlino stoici...@aol.com wrote:
 For the method invocation expression o.m, Ruby performs name
 resolution with the following steps: 1) first, it checks the
 eigenclass of o for singleton methods named m. 2) If no method m is
 found in the eigenclass, Ruby searches the class of the o for an
 instance method named m. 3) If no method m is found in the class, Ruby
 searches the instance methods of any modules included by the class of
 o. If that class includes more than one module, then they are searched
 in the reveerse of the order in which they wre included. That is, the
 most recently included module is searched first. If no instance method
 m is found in the class of o or in its modules, then the search moves
 up the inheirtance hierarchy to the superclass. Steps 2 and 3 are
 repeated for each class in the inheritance heirarchy until each
 ancestor class and its included modules have been searched. If no
 method named m is found after completing the search, then a method
 named method_missing is invoked instead. In order to find an
 appropriate definition of this method, the name resolution algorithm
 starts over at step 1. The kernel module provides a default
 implementation of method_missing, so this second pass of name
 resolution is guaranteed to succeed.

 Notice the part Steps 2 and 3 are repeated for each class in the
 inheritance heirarchy...

 What if the superclass has an eigenclass method? Why doesn't it repeat
 Step 1?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] global methods under object supposedly unaccessible

2012-09-23 Thread John Merlino
documentation:

By default, all methods in Ruby classes are public - accessible by
anyone. There are, nonetheless, only two exceptions for this rule: the
global methods defined under the Object class, and the initialize
method for any class. Both of them are implicitly private.


 class Object
 def something
 puts something
 end
 end
= nil
 class XYZ
 end
= nil
 xyz = XYZ.new
= #XYZ:0x10d067580
 xyz.something
something

So then why was I able to access something?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Class, Module, Object

2012-09-22 Thread John Merlino
 reload!
Reloading...
= true
 puts Class  Module
true
= nil
 puts Module  Class
false
= nil
 puts Module  Object
true
= nil
 puts Object  Module
false
= nil
 Object.parent
= Object

The above indicates that the Class object instance inherits from the
Module object instance and the Module object instance inherits from
Object. And Object doesn't inherit from anything.

So why do these return true:

 Module.is_a?(Class)
= true
 Object.is_a?(Module)
= true

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] in Rails, what is the main (global) scope called?

2012-09-21 Thread John Merlino
For example, you see files called

rails/actionpack/lib/action_controller/base.rb

which adds methods and such to the open module ActionController. What
scope is ActionController in? Is it just called the global scope?
Obviously, there is namespace resolution lookup. And a good example of
this is in the Base class of the same file. It references one module
like this: AbstractController::Layouts  and another module like this:
Rendering. One uses the :: namespace resolution operator, because
Layouts module is not within the scope that class Base is, which is
module ActionController scope, so it has to reference
AbstractController which must be in the GLOBAL scope in order for ruby
to find it and then it can look there to find Layouts. In contrast,
Rendering is defined within the ActionController scope, and since
class Base is defined within the ActionController scope as well, it
doesn't need to use the :: operator. It can simply search within that
scope and find the module Rendering. So what is that global scope that
ActionController and AbstractController are in within Rails?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: append_features(mod)

2012-09-20 Thread John Merlino
1.9.3p0 :003  class A
1.9.3p0 :004?   end
1.9.3p0 :009  A.is_a?(Module)
 = true
1.9.3p0 :010  A.is_a?(Class)
 = true
1.9.3p0 :011  Class.is_a?(Module)
 = true

class is module, so answer is append_features is run

On Sep 20, 1:23 am, John Merlino stoici...@aol.com wrote:
 append_features(mod)

 The documentation says:

 When this module is included in another, Ruby calls append_features in
 this module, passing it the receiving module in mod. Ruby’s default
 implementation is to add the constants, methods, and module variables
 of this module to mod if this module has not already been added to mod
 or one of its ancestors. See also Module#include.

 What if this module is included in a class, will append_features of
 this module still be called, passing in the class as mod? This is in
 particular reference to ActiveRecord::Concern, which has its own
 implementation of append_features overriding ruby's.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: append_features(mod)

2012-09-20 Thread John Merlino
So that explains a lot.

When module B is included in class C, we extend
ActiveSupport::Concern, which invokes the extended hook in the module
Concern, passing module B as local variable base. We want to indicate
that module B is a concern, so we set an instance variable
@_dependencies on it set to an empty array. Next, since B is included
in class C, the included hook in module B is called. The included hook
of ruby is overwritten by the included hook of ActiveSupport::Concern.
It checks if base was passed as the first argument to the included
hook, if not, the block passed to the included hook in module B (which
was included in class C) is set to the @_included_block instance
variable of Concern. Finally, since a class is an instance of Module,
a class is a module. Hence, since we included module B in class C
(which itself is a Module), the append_features hook is executed. What
append_features does is that when this module is included in another,
Ruby calls append_features in this module, passing it the receiving
module in mod. ActiveSupport::Concern captures the append_features
call and implements its own definition. The class C is passed as base
to append_features when module B is included in class C, and we check
if class C has the @_dependencies instance variable defined. Since we
did not extend ActiveSpport::Concern in class C, it does not have that
instance variable set, so the else clause is, in effect, triggered.
What we then do is iterate through each of the modules stored in
@_dependencies and include them in class C (base). We can have
multiple modules in the @_dependencies instance variable, and we have
them all included in base here, so that if one depends on another,
they are all available now in class C. It then extends ClassMethods
and includes InstanceMethods if they are defined in module B. It
finally invokes class_eval method on base (class C), passing in the
instance variable @_included_block if it is defined. @_included_block
stores the block that we passed into included call in module B, if we
did not pass an argument (other than the block) to the included call.
So that block gets evaluated in the class context of C, and hence we
can call class methods within that block. Next notice that module A is
included in module B. Ruby now evaluates module A. The extended method
is called, and it points to ActiveSupport::Concern again. So the
extended hook of Concern is invoked, we pass module A as local
variable base, and we set the @_dependencies instance variable to an
empty array. However, there is no included hook in module A, so that
is skipped. Ruby then invokes append_features, since module A was
included in module B. appended_features gets passed the receiving
module (module B) in module A context. We check if module B has the
@_dependencies instance method defined. It does actually (since
remember in module B we extended ActiveSupport::Concern which we did
not do in class A). So since module B has that instance variable set,
we simply include self (module A) into the array of modules held in
@_dependencies array. Hence, we can have a ton of modules stored in
@_dependencies by following the same process. Ultimately, all of the
modules will be included in the first module or class that does not
extend ActiveSupport::Concern. The reason why this is done is so that
module dependencies will be included when the module is included in
the parent class (or module). Apparently, ruby has no built in utility
to accomplish dependency resolution when one module depends on others
and that one module is included in a class.

On Sep 20, 8:11 pm, John Merlino stoici...@aol.com wrote:
 1.9.3p0 :003  class A
 1.9.3p0 :004?   end
 1.9.3p0 :009  A.is_a?(Module)
  = true
 1.9.3p0 :010  A.is_a?(Class)
  = true
 1.9.3p0 :011  Class.is_a?(Module)
  = true

 class is module, so answer is append_features is run

 On Sep 20, 1:23 am, John Merlino stoici...@aol.com wrote:







  append_features(mod)

  The documentation says:

  When this module is included in another, Ruby calls append_features in
  this module, passing it the receiving module in mod. Ruby’s default
  implementation is to add the constants, methods, and module variables
  of this module to mod if this module has not already been added to mod
  or one of its ancestors. See also Module#include.

  What if this module is included in a class, will append_features of
  this module still be called, passing in the class as mod? This is in
  particular reference to ActiveRecord::Concern, which has its own
  implementation of append_features overriding ruby's.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: multiple modules defining same method included into a class

2012-09-19 Thread John Merlino
Yep:

1.9.3p0 :005  module B
1.9.3p0 :006?   def name
1.9.3p0 :007? puts 'b module'
1.9.3p0 :008? end
1.9.3p0 :009?   end
 = nil
1.9.3p0 :010  module C
1.9.3p0 :011?   def name
1.9.3p0 :012? puts 'c module'
1.9.3p0 :013? end
1.9.3p0 :014?   end
 = nil
1.9.3p0 :015  class A
1.9.3p0 :016?   include B
1.9.3p0 :017?   include C
1.9.3p0 :018?   end
 = A
1.9.3p0 :019  A.new.name
c module
 = nil

On Sep 18, 9:14 am, Matt Jones al2o...@gmail.com wrote:
 On Monday, 17 September 2012 21:04:58 UTC-4, John Merlino wrote:

  In Ruby, classes are never closed: you can always add methods to an
  existing class. This applies to the classes you write as well as the
  standard, built-in classes. All you have to do is open up a class
  definition for an existing class, and the new contents you specify
  will be added to whatever's there. In the same regard, if module is
  used with the name of a pre-existing module that module is re-opened.
  If a method is defined in a re-opened module with the same name as a
  pre-existing method in the same module the old method is overwritten
  with the new. And, of course, modules can be made immutable,
  effectively preventing them from being reopened by freezing the module
  object. Frozen modules raise RuntimeErrors when methods are defined,
  or variables manipulated, in their context.

  When you include a module in a class, without a prefix (prefix meaning
  something like this: AbstractController::Layouts), then ruby searches
  for the module of that name within the scope of the current module
  wrapping the class that the include was called in.

  So, for example:

  module ActionController
    class Base
      include Rendering

  Since we include Rendering within the scope of the Base class
  object, ruby first looksup the constant Rendering, that is, looking
  for a module named Rendering in the ActionController namespace, since
  that is the namesapce that Base is defined in???

  Well, ActionController module does define a module named Rendering:

  module ActionController
    module Rendering
       def render(*args)
        raise ::AbstractController::DoubleRenderError if response_body
        super
        self.content_type ||= Mime[lookup_context.rendered_format].to_s
        response_body
      end

  So now the method render(*args) is included in the Base class as an
  instance method. So when we call, for example, (hypothetically)
  ActionView::Base.new.render :action = my_action, :layout = false,
  ActionView::Base is instantiated and we invoke the render instance
  method, and since no render method is declared in the Base class
  context, ruby scope chain does lookup into the module Rendering and
  finds the method so calls it. Now, as you may know, it's possible to
  pass multiple kinds of arguments to render, depending on whether you
  want to render a template or a partial or file, etc. The * syntax does
  the job here, allowing you vary the number of arguments passed. It
  checks if there is already a response to the request, and raises an
  Exception, if so. Otherwise, it calls super.

  During this super call, I got a little confused. In
  ActionController::Base, there is another module included called
  AbstractController::Layouts. Layouts in turn includes a module called
  Rendering. Since there is a Rendering module within the
  AbstractController namespace, it is found, and it indeed contains a
  method called render.

     def render(*args, block)
        options = _normalize_render(*args, block)
        self.response_body = render_to_body(options)
      end

  And because render is included in Layouts, it's included as an
  instance method, and because Layouts was included in
  ActionController::Base, that render method utlimately makes its way up
  to the Base class. Now we have two modules
  (ActionController::Rendering and AbstractController::Rendering that
  are including this method into Base. So why doesn't one of them get
  overwritten? Why does the call to super work?

 The modules aren't included exactly - they're just added to the list of
 ancestors (try ActionController::Base.ancestors for an eyeful) where
 methods are looked up. Modules included later in the source are higher on
 the list (similar to subclass methods vs. base class methods) and calling
 'super' simply specifies that the *next* available method up the chain
 should be called. This works (as of recent Rails versions) for generated
 methods as well:

 class SomeModel  ActiveRecord::Base
   has_many :wats

   def wats
     # calling 'super' here hits the generated accessor from has_many
   end
 end

 There's one additional wrinkle for many of the modules in Rails itself -
 many of them are extended with ActiveSupport::Concern, which tidies a bunch
 of things up and (most relevant here) changes the semantics of include
 SomeOtherModule. See this article for more:

 http://opensoul.org/blog/archives/2011/02/07/concerning-activesupport...

 --Matt Jones

-- 
You

[Rails] append_features(mod)

2012-09-19 Thread John Merlino
append_features(mod)

The documentation says:

When this module is included in another, Ruby calls append_features in
this module, passing it the receiving module in mod. Ruby’s default
implementation is to add the constants, methods, and module variables
of this module to mod if this module has not already been added to mod
or one of its ancestors. See also Module#include.

What if this module is included in a class, will append_features of
this module still be called, passing in the class as mod? This is in
particular reference to ActiveRecord::Concern, which has its own
implementation of append_features overriding ruby's.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: inheriting from StandardError

2012-09-17 Thread John Merlino
So we must build an entire class just for sake of more specific rescue
statements:

class MyError  StandardError
end

try_counter = 0
begin
 try_counter += 1
 puts 'Here 1'
 raise MyError.new Text unless try_counter  5
 puts 'Here 2'
rescue MyError
 puts 'Here 3 - MyError encountered'
 retry
rescue StandardError
 puts Here 4 - Other error encountered (#{$!.inspect}) +
caller.inspect
 raise
else
 puts 'Here 5 - No errors'
ensure
 puts 'Here 6 - Always done'
end


On Sep 16, 4:02 pm, Frederick Cheung frederick.che...@gmail.com
wrote:
 On Sunday, September 16, 2012 7:57:44 PM UTC+1, John Merlino wrote:

    class ActionNotFound  StandardError #:nodoc:
    end

  unless action_name = method_for_action(action_name)
    raise ActionNotFound, The action '#{action}' could not be found for
  #{self.class.name}
  end

  But why even bother to create the subclasses (which as shown above,
  have no definition of themselves), when substituting ActionNotFound
  with StandardError during the raise call will have the same effect.

 Because it doesn't have the same effect. Raising specific subclasses allows
 you to write targeted rescue clauses rather than rescuing indiscriminately.

 Fred

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] multiple modules defining same method included into a class

2012-09-17 Thread John Merlino
In Ruby, classes are never closed: you can always add methods to an
existing class. This applies to the classes you write as well as the
standard, built-in classes. All you have to do is open up a class
definition for an existing class, and the new contents you specify
will be added to whatever's there. In the same regard, if module is
used with the name of a pre-existing module that module is re-opened.
If a method is defined in a re-opened module with the same name as a
pre-existing method in the same module the old method is overwritten
with the new. And, of course, modules can be made immutable,
effectively preventing them from being reopened by freezing the module
object. Frozen modules raise RuntimeErrors when methods are defined,
or variables manipulated, in their context.

When you include a module in a class, without a prefix (prefix meaning
something like this: AbstractController::Layouts), then ruby searches
for the module of that name within the scope of the current module
wrapping the class that the include was called in.

So, for example:

module ActionController
  class Base
include Rendering

Since we include Rendering within the scope of the Base class
object, ruby first looksup the constant Rendering, that is, looking
for a module named Rendering in the ActionController namespace, since
that is the namesapce that Base is defined in???

Well, ActionController module does define a module named Rendering:

module ActionController
  module Rendering
 def render(*args)
  raise ::AbstractController::DoubleRenderError if response_body
  super
  self.content_type ||= Mime[lookup_context.rendered_format].to_s
  response_body
end


So now the method render(*args) is included in the Base class as an
instance method. So when we call, for example, (hypothetically)
ActionView::Base.new.render :action = my_action, :layout = false,
ActionView::Base is instantiated and we invoke the render instance
method, and since no render method is declared in the Base class
context, ruby scope chain does lookup into the module Rendering and
finds the method so calls it. Now, as you may know, it's possible to
pass multiple kinds of arguments to render, depending on whether you
want to render a template or a partial or file, etc. The * syntax does
the job here, allowing you vary the number of arguments passed. It
checks if there is already a response to the request, and raises an
Exception, if so. Otherwise, it calls super.

During this super call, I got a little confused. In
ActionController::Base, there is another module included called
AbstractController::Layouts. Layouts in turn includes a module called
Rendering. Since there is a Rendering module within the
AbstractController namespace, it is found, and it indeed contains a
method called render.

   def render(*args, block)
  options = _normalize_render(*args, block)
  self.response_body = render_to_body(options)
end

And because render is included in Layouts, it's included as an
instance method, and because Layouts was included in
ActionController::Base, that render method utlimately makes its way up
to the Base class. Now we have two modules
(ActionController::Rendering and AbstractController::Rendering that
are including this method into Base. So why doesn't one of them get
overwritten? Why does the call to super work?






-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: multiple modules defining same method included into a class

2012-09-17 Thread John Merlino
So it does appear that the ActionController::Rendering module does
include AbstractController::Rendering, which means a call to super in
the render method of  ActionController::Rendering will in turn call
the render method of  AbstractController::Rendering. What makes this
somewhat confusing is that ActionController::Rendering is included in
ActionController::Base, but  AbstractController::Rendering is included
in ActionController::Base as well. Yet  AbstractController::Rendering
is also included in ActionController::Rendering. Wouldn't
AbstractController::Rendering being included
ActionController::Rendering and the fact that
ActionController::Rendering is included in ActionController::Base make
AbstractController::Rendering being included in ActionController::Base
redundant?

On Sep 17, 9:04 pm, John Merlino stoici...@aol.com wrote:
 In Ruby, classes are never closed: you can always add methods to an
 existing class. This applies to the classes you write as well as the
 standard, built-in classes. All you have to do is open up a class
 definition for an existing class, and the new contents you specify
 will be added to whatever's there. In the same regard, if module is
 used with the name of a pre-existing module that module is re-opened.
 If a method is defined in a re-opened module with the same name as a
 pre-existing method in the same module the old method is overwritten
 with the new. And, of course, modules can be made immutable,
 effectively preventing them from being reopened by freezing the module
 object. Frozen modules raise RuntimeErrors when methods are defined,
 or variables manipulated, in their context.

 When you include a module in a class, without a prefix (prefix meaning
 something like this: AbstractController::Layouts), then ruby searches
 for the module of that name within the scope of the current module
 wrapping the class that the include was called in.

 So, for example:

 module ActionController
   class Base
     include Rendering

 Since we include Rendering within the scope of the Base class
 object, ruby first looksup the constant Rendering, that is, looking
 for a module named Rendering in the ActionController namespace, since
 that is the namesapce that Base is defined in???

 Well, ActionController module does define a module named Rendering:

 module ActionController
   module Rendering
      def render(*args)
       raise ::AbstractController::DoubleRenderError if response_body
       super
       self.content_type ||= Mime[lookup_context.rendered_format].to_s
       response_body
     end

 So now the method render(*args) is included in the Base class as an
 instance method. So when we call, for example, (hypothetically)
 ActionView::Base.new.render :action = my_action, :layout = false,
 ActionView::Base is instantiated and we invoke the render instance
 method, and since no render method is declared in the Base class
 context, ruby scope chain does lookup into the module Rendering and
 finds the method so calls it. Now, as you may know, it's possible to
 pass multiple kinds of arguments to render, depending on whether you
 want to render a template or a partial or file, etc. The * syntax does
 the job here, allowing you vary the number of arguments passed. It
 checks if there is already a response to the request, and raises an
 Exception, if so. Otherwise, it calls super.

 During this super call, I got a little confused. In
 ActionController::Base, there is another module included called
 AbstractController::Layouts. Layouts in turn includes a module called
 Rendering. Since there is a Rendering module within the
 AbstractController namespace, it is found, and it indeed contains a
 method called render.

    def render(*args, block)
       options = _normalize_render(*args, block)
       self.response_body = render_to_body(options)
     end

 And because render is included in Layouts, it's included as an
 instance method, and because Layouts was included in
 ActionController::Base, that render method utlimately makes its way up
 to the Base class. Now we have two modules
 (ActionController::Rendering and AbstractController::Rendering that
 are including this method into Base. So why doesn't one of them get
 overwritten? Why does the call to super work?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] inheriting from StandardError

2012-09-16 Thread John Merlino
I often see custom Exception classes inheriting from StandardError.
Errors which you can generally deal with are subclassed from
StandardError:

module AbstractController
  class Error  StandardError #:nodoc:
  end

  class ActionNotFound  StandardError #:nodoc:
  end

unless action_name = method_for_action(action_name)
  raise ActionNotFound, The action '#{action}' could not be found for
#{self.class.name}
end

But why even bother to create the subclasses (which as shown above,
have no definition of themselves), when substituting ActionNotFound
with StandardError during the raise call will have the same effect.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: inheriting from StandardError

2012-09-16 Thread John Merlino
I would understand if there was some level of customization involved
that distinguishes it from the super class:

class DoubleRenderError  Error
DEFAULT_MESSAGE = Render and/or redirect were called multiple
times in this action. Please note that you may only call render OR
redirect, and at most once per action. Also note that neither redirect
nor render terminate execution of the action, so if you want to exit
an action after redirecting, you need to do something like
\redirect_to(...) and return\.

def initialize(message = nil)
  super(message || DEFAULT_MESSAGE)
end
  end

But in the exampels I provided in the initial post that was not the
case. ActionNotFound, for example, had no implementation of its own.
It seems to be a waste of memory allocation.

On Sep 16, 2:57 pm, John Merlino stoici...@aol.com wrote:
 I often see custom Exception classes inheriting from StandardError.
 Errors which you can generally deal with are subclassed from
 StandardError:

 module AbstractController
   class Error  StandardError #:nodoc:
   end

   class ActionNotFound  StandardError #:nodoc:
   end

 unless action_name = method_for_action(action_name)
   raise ActionNotFound, The action '#{action}' could not be found for
 #{self.class.name}
 end

 But why even bother to create the subclasses (which as shown above,
 have no definition of themselves), when substituting ActionNotFound
 with StandardError during the raise call will have the same effect.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] formats in action view base

2012-09-15 Thread John Merlino
When you invoke ActionView::Base, it in turn invokes a LookupContext
object. The LookupContext class object has some class level macros
that builds some instance methods corresponding to a format:




register_detail(:formats) { ActionView::Base.default_formats ||
[:html, :text, :js, :css,  :xml, :json] }
 def self.register_detail(name, options = {}, block)
  self.registered_details  name
  initialize = registered_details.map { |n| @details[:#{n}] =
details[:#{n}] || default_#{n} }

  Accessors.send :define_method, :default_#{name}, block
  Accessors.module_eval -METHOD, __FILE__, __LINE__ + 1
def #{name}
  @details.fetch(:#{name}, [])
end

def #{name}=(value)
  value = value.present? ? Array(value) : default_#{name}
  _set_detail(:#{name}, value) if value != @details[:#{name}]
end

remove_possible_method :initialize_details
def initialize_details(details)
  #{initialize.join(\n)}
end
  METHOD
end


So these methods are included as instance methods via the Accessors
module. Later the LookupContext class override the formats method with
its own definition:

def formats=(values)
  if values
values.concat(default_formats) if values.delete */*
if values == [:js]
  values  :html
  @html_fallback_for_js = true
end
  end
  super(values)
end

1) So what was the purpose of adding a formats method to the Accessors
module and then include it into LookupContext, if it will always be
overriden by LookupContext's own implementation?

2) What is meant by expand [*/*] values in the comment # Override
formats= to expand [*/*] values  which is directly above the
formats implementation on LookupContext?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: formats in action view base

2012-09-15 Thread John Merlino
 that this would in turn invoke the formats method that
we included from our Accessors module to the LookupContext class.
However, the way the call chain works is that the class context is
looked up prior to the modules included into that class context. In
the class context, we actually do define the formats method, so this
gets invoked instead of the one defined in the Accessors module. Let's
say the format value we passed it was the symbol :js, representing the
ubiquitous javascript scripting language. I think */* refers to all
possible formats (please help, I'm not sure about that...). So if
values array contains the string */* in its index, then we merge
with it the returned array of default_formats, which is
 [:html, :text, :js, :css,  :xml, :json]. We also check if the
parameter is [:js]. If so, we add :html as fallback to :js. We also
set the @html_fallback_for_js instance variable to true, just in case
we ever need to check if we already set the html as a default to
javascript.

    def formats=(values)
      if values
        values.concat(default_formats) if values.delete */*
        if values == [:js]
          values  :html
          @html_fallback_for_js = true
        end
      end
      super(values)
    end


7) This is where I am really unsure. We then call the same setter
method of the super class passing in our values array. The
LookupContext class does not inherit from any other class. However,
the Accessors module is included in it, which does define a formats
setter method so I think this is what gets called next. If this is the
case, then what happens next is the setter method we dynamically
created when the class was loaded gets called (which we included from
the Accessors module), and we encapsulate the value into an array. We
check if @details instance variable :formats key already has that
value, and if not then we make a copy of @details and set the value to
the :formats key. (Another question why do we make a copy?)

    protected

      def _set_detail(key, value)
        @details = @details.dup if @details_key
        @details_key = nil
        @details[key] = value
      end

This is my assessment of the sequence of actions. My main question is
if it's true that a call to super in an instance method will call the
method in an included module of the same name, as shown in the example
provided above, with detailed descriptions.









On Sep 15, 2:25 pm, John Merlino stoici...@aol.com wrote:
 When you invoke ActionView::Base, it in turn invokes a LookupContext
 object. The LookupContext class object has some class level macros
 that builds some instance methods corresponding to a format:

     register_detail(:formats) { ActionView::Base.default_formats ||
 [:html, :text, :js, :css,  :xml, :json] }
  def self.register_detail(name, options = {}, block)
       self.registered_details  name
       initialize = registered_details.map { |n| @details[:#{n}] =
 details[:#{n}] || default_#{n} }

       Accessors.send :define_method, :default_#{name}, block
       Accessors.module_eval -METHOD, __FILE__, __LINE__ + 1
         def #{name}
           @details.fetch(:#{name}, [])
         end

         def #{name}=(value)
           value = value.present? ? Array(value) : default_#{name}
           _set_detail(:#{name}, value) if value != @details[:#{name}]
         end

         remove_possible_method :initialize_details
         def initialize_details(details)
           #{initialize.join(\n)}
         end
       METHOD
     end

 So these methods are included as instance methods via the Accessors
 module. Later the LookupContext class override the formats method with
 its own definition:

     def formats=(values)
       if values
         values.concat(default_formats) if values.delete */*
         if values == [:js]
           values  :html
           @html_fallback_for_js = true
         end
       end
       super(values)
     end

 1) So what was the purpose of adding a formats method to the Accessors
 module and then include it into LookupContext, if it will always be
 overriden by LookupContext's own implementation?

 2) What is meant by expand [*/*] values in the comment # Override
 formats= to expand [*/*] values  which is directly above the
 formats implementation on LookupContext?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] calling method on base intended to simulate initialize on instances?

2012-09-13 Thread John Merlino
class A
  def initialize
setup_b
setup_c
  end

  def b_and_c
   #{@b} and #{@c}
  end

private
 def setup_b
@b = 'b'
  end

  def setup_c
@c = 'c'
  end

  def setup_d
@d = 'd'
  end
end

a = A.new
a.instance_variable_get(@b) # = b
a.instance_variable_get(@c) # = c
a.instance_variable_get(@d) # = nil
a = A.new.b_and_c # = b and c


Now what I did above is to make a point. initialize allows us to
create some initial setup for new objects, so that when we call a
public method like b_and_c, we can expect certain values back based on
the initialization hook that must occur first. From my understanding,
modules do not have an initialize method, so then how do you simulate
it? Well, I was looking at Rails and notice this:

 class Template
module Handlers
  autoload :ERB, 'action_view/template/handlers/erb'
  autoload :Builder, 'action_view/template/handlers/builder'
  autoload :Raw, 'action_view/template/handlers/raw'

  def self.extended(base)
base.register_default_template_handler :erb, ERB.new
base.register_template_handler :builder, Builder.new
base.register_template_handler :raw, Raw.new
  end

  @@template_handlers = {}
  @@default_template_handlers = nil

  def self.extensions
@@template_extensions ||= @@template_handlers.keys
  end

  def register_default_template_handler(extension, klass)
register_template_handler(extension, klass)
@@default_template_handlers = klass
  end

 def register_template_handler(extension, handler)
@@template_handlers[extension.to_sym] = handler
@@template_extensions = nil
  end

 class Template
extend Template::Handlers


class LookupContext
   register_detail(:handlers){ Template::Handlers.extensions }


Basically, when ruby loads the Template class (I will assume that it
must be loaded prior to Handlers module or LookupContext class), it
immediately executes a class method, which is called extend, and
passes the module Handlers as the lone argument. What the extend
method does is copy the methods of the module Handlers to the Template
class as class methods. But what else happens is the self.extended
hook is immediately triggered, just as initialize is when you
instantiate a class. We pass our Template class object as the
parameter base. And we call the register_default_template_handler
method (which is now a class method of Template), passing it a
symbol :erb and an instance of ERB, which returns a string from
call(). We in turn call register_template_handler, passing in the same
two arguments. We simply append the key/value pair to the
@@template_handlers class variable, which is a hash data type, and
allows us to add a number of key/value pairs corresponding to
extensions and template types. (e.g. :erb extension corresponding to
an ERB template type). Hence, when we invoke the module method
extensions on the module, it can return a value for the
@@template_handlers class variable, since it was initialized with
values during the hook, prior to the extensions method call.

I have a few questions about this.

1) Is is true to say that the class variables of the module get
initialized prior than the extended hook. Reason why say this is that
the extended hook calls a method that expects the variable to be set
already.

2) Do all the methods of the module get copied over to base (Template
class object) prior to the hook being called? Reason why I say this is
because we call base.register_default_template_handler, where base is
Tempalte object an register_default_template_handler is defined in the
module that gets copied to base as a class method via extend. Hence,
in order for base.register_default_template_handler to work, the
methods must have been copied first.

3) Can anyone tell me what @@template_extensions is for? I dont see
that initialized with a value anywhere other than nil.

thanks for response


-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] define_method vs module_eval

2012-09-11 Thread John Merlino
Rails code:

 Accessors.send :define_method, :default_#{name}, block

Accessors.module_eval -METHOD, __FILE__, __LINE__ + 1
    def #{name}
    @details.fetch(:#{name}, [])
    end

    def #{name}=(value)
    value = value.present? ? Array(value) : default_#{name}
    _set_detail(:#{name}, value) if value != @details[:#{name}]
    end

    remove_possible_method :initialize_details
    def initialize_details(details)
    #{initialize.join(\n)}
    end
    METHOD
end

Here we invoke send() on the module Accessors, passing
the :define_method symbol, which represents the define_method private
method available from Class class. We create an instance method called
default_locale, whose value is the block passed from register_detail
class method of ActionView::LookupContext. Note that we later use
include Accessors within LookupContext class to make that available
as an instance method of LookupContext. We then create more instance
methods using module_eval, with here-documents to specify our
delimiter (METHOD) and the dynamic constants (__FILE__, __LINE__) for
accurate error reporting on stacktrace. My question is why not include
default_#{name} as part of the evaluated string in module_eval, rather
than invoking send() directly above that using define_method?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: mattr_accessor inside a class

2012-09-10 Thread John Merlino
it looks as if it is onyl available on the class because if you look
it says self.class.fallbacks, yet that wouldnt make sense either
because then what would be the point of its existance if you had to
reach the class for it it, why not just create a class level macro
instead?

On Sep 9, 3:10 pm, John Merlino stoici...@aol.com wrote:
 Rails extends Ruby with mattr_accessor (Module accessor). As Ruby's
 attr_accessor generates getter/setter methods for instances,
 mattr_accessor provide getter/setter methods at the module level. In
 below example, you see that mattr_accessor declared in the class
 context of LookupContext. It's declared in class, not module. However,
 modules are defined in LookupContext, for example, the module
 ViewPaths, which makes use of the accessor. So is it safe to say that
 if a module accessor is declared in class, then it can only be
 available to modules of that class?

   class LookupContext
     mattr_accessor :fallbacks
     module ViewPaths
       self.class.fallbacks.each do |resolver|

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: dash symbol

2012-09-09 Thread John Merlino
ok this was oversight on my part. First of all, instead of using the
helper helper in the console, you can directly access actionview just
by specifying the constant. So
ActionView::Helpers::FormBuilder.instance_methods would work. But what
was oversight is that I was wondering that FormBuilder's field_helpers
class method which returns an array of methods for the object was
actually removing all the methods it defines. But if you look at its
assignment, it is grabbing the methods of FormHelper, not FormBuilder.
It does FormHelper.instance_methods and FormHelper is what defines
the key methods that we often invoke on the form builder that have
generic output:

ActionView::Helpers::FormHelper.instance_methods
 =
[:convert_to_model, :form_for, :fields_for, :label, :text_field, 
:password_field, :hidden_field, :file_field, :text_area, :check_box, 
:radio_button, :search_field, :telephone_field, :phone_field, :url_field, 
:email_field, :number_field, :range_field]

The reason why we
exclude :label, :check_box, :radio_button, :fields_for, :hidden_field, 
:file_field
is because they have their own unqiue definition which is done in the
form builder itself.

So whene we cal text_field, for example, that method was dybamically
built using class_eval. and what it does is just call the method from
selector.inspect on tempalte, and of course the tempalte is
ActionView::Helpers::FormHelper, since that is also where form_for
itself is defined. and in our view we invoke form_for, where self is
ActionView with tha tmodule included.

On Sep 8, 3:51 pm, John Merlino stoici...@aol.com wrote:
 Yeah so I would like to see the returned array of instance methods of
 field_helpers of FormBuilder. I try to return it in console:

 1.9.3p0 :016  FormBuilder.field_helpers
 NoMethodError: undefined method `field_helpers' for FormBuilder:Class

 Why is it saying undefined method field_helpers when that method
 exists on the FormBuilder class:

 class_attribute :field_helpers

 On Sep 8, 2:49 pm, Jordon Bedwell envyge...@gmail.com wrote:







  In ruby a minus on an array removes elements.   So its removing elements
  from the array.
  On Sep 8, 2012 1:42 PM, John Merlino stoici...@aol.com wrote:

   In the example below, what is the dash doing between the class
   attribute and array:

   (field_helpers -
   [:label, :check_box, :radio_button, :fields_for, :hidden_field,
   :file_field]).each
   do |selector|

   --
   You received this message because you are subscribed to the Google Groups
   Ruby on Rails: Talk group.
   To post to this group, send email to rubyonrails-talk@googlegroups.com.
   To unsubscribe from this group, send email to
   rubyonrails-talk+unsubscr...@googlegroups.com.
   For more options, visithttps://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] What module are the % % and %= % defined in?

2012-09-09 Thread John Merlino
What module of ActionView are the % % and %= % defined in?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: What module are the % % and %= % defined in?

2012-09-09 Thread John Merlino
ok ActionView::Base includes this module ::ERB::Util and ERB class
seems to do so

On Sep 9, 1:53 pm, John Merlino stoici...@aol.com wrote:
 What module of ActionView are the % % and %= % defined in?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] mattr_accessor inside a class

2012-09-09 Thread John Merlino
Rails extends Ruby with mattr_accessor (Module accessor). As Ruby's
attr_accessor generates getter/setter methods for instances,
mattr_accessor provide getter/setter methods at the module level. In
below example, you see that mattr_accessor declared in the class
context of LookupContext. It's declared in class, not module. However,
modules are defined in LookupContext, for example, the module
ViewPaths, which makes use of the accessor. So is it safe to say that
if a module accessor is declared in class, then it can only be
available to modules of that class?

  class LookupContext
mattr_accessor :fallbacks
module ViewPaths
  self.class.fallbacks.each do |resolver|

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] LookupContext missing constructor

2012-09-09 Thread John Merlino
The title of this message is wrong. LookupContext must have a
constructor:

ActionView::LookupContext.new(nil)
 = #ActionView::LookupContext:0x007f8e84755d18 @details_key=nil,
@details={:handlers=[:erb, :builder, :coffee], :formats=[:html, :text, :js, 
:css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, 
:json], :locale=[:en, :en]},
@skip_default_locale=false, @frozen_formats=false, @cache=true,
@prefixes=[], @view_paths=[]

My problem is I can't find it:

https://github.com/rails/rails/blob/master/actionpack/lib/action_view/lookup_context.rb


There's other initialize methods for other classes, but not for
LookupContext. Where is it?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: LookupContext missing constructor

2012-09-09 Thread John Merlino
I think I found it on line 170:

def initialize(view_paths, details = {}, prefixes = [])
  @details, @details_key = {}, nil
  @skip_default_locale = false
  @cache = true
  @prefixes = prefixes
  @rendered_format = nil

  self.view_paths = view_paths
  initialize_details(details)
end

It's after 3 module definitions of the same class. It seems almost
intentionally designed to be confusing.

On Sep 9, 3:25 pm, John Merlino stoici...@aol.com wrote:
 The title of this message is wrong. LookupContext must have a
 constructor:

 ActionView::LookupContext.new(nil)
  = #ActionView::LookupContext:0x007f8e84755d18 @details_key=nil,
 @details={:handlers=[:erb, :builder, :coffee], :formats=[:html, :text, :js, 
 :css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, 
 :url_encoded_form, :json], :locale=[:en, :en]},
 @skip_default_locale=false, @frozen_formats=false, @cache=true,
 @prefixes=[], @view_paths=[]

 My problem is I can't find it:

 https://github.com/rails/rails/blob/master/actionpack/lib/action_view...

 There's other initialize methods for other classes, but not for
 LookupContext. Where is it?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] misleading variable value

2012-09-09 Thread John Merlino
I'm going to invoke action view base from console, passing a string
object:

1.9.3p0 :016  ActionView::Base.new('app/views')

 = #ActionView::Base:0x007fd95c5e8f48 @_config={},
@view_renderer=#ActionView::Renderer:0x007fd95c5e8c50
@lookup_context=#ActionView::LookupContext:0x007fd95c5e8ed0
@details_key=nil,
@details={:handlers=[:erb, :builder, :coffee], :formats=[:html, :text, :js, 
:css, :ics, :csv, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, 
:json], :locale=[:en, :en]},
@skip_default_locale=false, @frozen_formats=false, @cache=true,
@prefixes=[], @view_paths=[/Users/johnmerlino/github/my_diet/app/
views], @_assigns={}, @_controller=nil,
@view_flow=#ActionView::OutputFlow:0x007fd95c5e8c28 @content={},
@output_buffer=nil, @virtual_path=nil


Look at the return value assigned to @view_paths. It should not be an
array. It should be a PathSet object instance, which has an instance
variable called @paths, which holds an array of
OptimizedFileSystemResolver object instances, which themselves hold a
@path instance variable that is the very string represented in that
@view_paths array above. So what's going on?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] dash symbol

2012-09-08 Thread John Merlino
In the example below, what is the dash doing between the class
attribute and array:

(field_helpers -
[:label, :check_box, :radio_button, :fields_for, :hidden_field, 
:file_field]).each
do |selector|

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: dash symbol

2012-09-08 Thread John Merlino
Yeah so I would like to see the returned array of instance methods of
field_helpers of FormBuilder. I try to return it in console:

1.9.3p0 :016  FormBuilder.field_helpers
NoMethodError: undefined method `field_helpers' for FormBuilder:Class

Why is it saying undefined method field_helpers when that method
exists on the FormBuilder class:

class_attribute :field_helpers

On Sep 8, 2:49 pm, Jordon Bedwell envyge...@gmail.com wrote:
 In ruby a minus on an array removes elements.   So its removing elements
 from the array.
 On Sep 8, 2012 1:42 PM, John Merlino stoici...@aol.com wrote:







  In the example below, what is the dash doing between the class
  attribute and array:

  (field_helpers -
  [:label, :check_box, :radio_button, :fields_for, :hidden_field,
  :file_field]).each
  do |selector|

  --
  You received this message because you are subscribed to the Google Groups
  Ruby on Rails: Talk group.
  To post to this group, send email to rubyonrails-talk@googlegroups.com.
  To unsubscribe from this group, send email to
  rubyonrails-talk+unsubscr...@googlegroups.com.
  For more options, visithttps://groups.google.com/groups/opt_out.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] not seeing where name attribute is added to input fields

2012-09-08 Thread John Merlino
Without going to detail, I'll just show important code:

text field is passed the name of object, could be a symbol (:user) or
string (user[]). method is datbase attribute or virtual attribute.
the options hash, among other things, includes the object if persisted
(e.g. @user).
  def text_field(object_name, method, options = {})
Tags::TextField.new(object_name, method, self, options).render
  end

TextField doesn't have initialize, it calls on super which is Base,
and we create some instance variables holding our object information
and so forth:
class Base
...

def initialize(object_name, method_name, template_object,
options = {})
  @object_name, @method_name = object_name.to_s.dup,
method_name.to_s.dup
  @template_object = template_object

  @object_name.sub!(/\[\]$/,) || @object_name.sub!(/\[\]\]
$/,])
  @object = retrieve_object(options.delete(:object))
  @options = options
...

We call render on text field object
def render
  options = @options.stringify_keys
  options[size] = options[maxlength] unless options.key?
(size)
  options[type]  ||= field_type
  options[value] = options.fetch(value)
{ value_before_type_cast(object) } unless field_type == file
  options[value] = ERB::Util.html_escape(options[value])
  add_default_name_and_id(options)
  tag(input, options)
end

  def tag(name, options = nil, open = false, escape = true)
#{name}#{tag_options(options, escape) if options}#{open ?
 :  /}.html_safe
  end

and thats pretty much it. Wheres the name attribute and its value
appended to the returned string from render?

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] :index = nil

2012-09-07 Thread John Merlino
On here:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box-label-Gotcha

you see this code:

%= fields_for project[invoice_attributes][], invoice, :index = nil
do |form| %
  %= form.check_box :paid %
  ...
% end %


why are they using :index = nil in the example? I mean I know that
what it does is ensure that the invoice objects do not get passed an
index number so that you have this: project[invoice_attributes][]
rather than this: project[invoice_attributes][1]. But why in the above
example, do they want to achieve this? It seems as though invoice is
an existing object and therefore is not a new record.

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




[Rails] Re: Regexp pre_match

2012-09-06 Thread John Merlino
yep, last_match returns a MatchData object, which contains some
wrapper methods, including a string of the last successful pattern
match. Hence, pre_match would fall under MatchData, not Regexp.

On Sep 6, 10:21 am, Rick richard.t.ll...@gmail.com wrote:
 http://www.ruby-doc.org/core-1.9.3/MatchData.html#method-i-pre_match







 On Thursday, September 6, 2012 1:40:31 AM UTC-4, John Merlino wrote:

  I looked in ruby documentation

 http://www.ruby-doc.org/core-1.9.3/Regexp.html

  I cannot find a method called pre_match but its used in Rails...

  @template.instance_variable_get(@#{Regexp.last_match.pre_match})

-- 
You received this message because you are subscribed to the Google Groups Ruby 
on Rails: Talk group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.




  1   2   3   4   >