how does this work?
in irb:
>> class A
>> b = [1, 2,3]
>> end
=> [1, 2, 3]
Is b an instance variable? class variable? how would I access b from
outside the class? Is it used for meta-programming?
I'm trying to give a file as input, have it changed within the program, and save the result to a file that is output. But the output file is the same as the input file. :/ Total n00b question, but what am I doing wrong?:
puts "Reading Celsius temperature value from data file..."
num = File.read("temperature.dat")
celsius = num.to_i
farenheit = (celsius * 9/5) + 32
puts "Saving result to output file 'faren_temp.out'"
fh = File.new("faren_temp.out", "w")
fh.puts farenheit
fh.close
So, I'd like to be able to make a call
x = MyClass.new('good morning', 'good afternoon', 'good evening', 'good night',
['hello', 'goodbye'])
that would add methods to the class whose values are the values of the arguments. So now:
p x.methods #> [m_greeting, a_greeting, e_greeting, n_greeting,
r_greeting, ...]
And
p x.m_greeting #> "good morning"
p x.r_greeting #> ['hello', 'goodbye']
I realize that this is sort of what instance variables are to do (and that if I wanted them immutable I could make them frozen constants) but, for reasons beyond my control, I need to make methods instead.
Thanks!
i am wrking on tag clouds with wp columns ( java script) but it s not wrking .It contains files like tagcloud.swf and swfobject.js . I have added this file in public folder and added html.erb file in the view but its not generating the code and showing any thing on the page
the code is
<%= javascript_include_tag 'swfobject.js' %>
<style type="text/css">
body { background-color: #eee; padding: 20px; }
</style>
<% tags = (current_user.all_tags) %
<% all_tags = tags.flatten.uniq%
<script type="text/javascript">
var so = new SWFObject("/tagcloud.swf", "tagcloud", "600", "400", "7", "#ffffff");
// uncomment next line to enable transparency
//so.addParam("wmode", "transparent");
so.addVariable("tcolor", "0x333333");
so.addVariable("mode", "tags");
so.addVariable("distr", "true");
so.addVariable("tspeed", "100");
so.addVariable("tagcloud", "<tags>
<% for t in all_tags %>
<a href='#' style='22' color='0xff0000' hicolor='0x00cc00'><%=t.to_s%></a>
<%#= link_to t.to_s ,tag_index_path(t) %>
<% end %></tags>");
so.write("flashcontent");
</script></body>
If i had a list of balls each of which has a color property. how can i cleanly get the list of balls with the most frequent color.
[m1,m2,m3,m4]
say,
m1.color = blue
m2.color = blue
m3.color = red
m4.color = blue
[m1,m2,m4] is the list of balls with the most frequent color
My Approach is to do:
[m1,m2,m3,m4].group_by{|ball| ball.color}.each do |samecolor|
my_items = samecolor.count
end
where count is defined as
class Array
def count
k =Hash.new(0)
self.each{|x|k[x]+=1}
k
end
end
my_items will be a hash of frequencies foreach same color group. My implementation could be buggy and i feel there must be a better and more smarter way.
any ideas please?
So here's the output of inspect on a class:
<Recurly::BillingInfo::CreditCard:0x1036a8a98 @prefix_options={}, @attributes={"month"=>1, "last_four"=>"1", "type"=>"bogus", "year"=>2010}>
I'm trying to get the type attribute but seems that might be some sort of reserved word?
Here's the full rundown of what I'm trying to do
@charges = Recurly::BillingInfo.find('123')
@charges.credit_card.type
So, how can I get type from that?
module MyModule
def my_method; 'hello'; end
end
class MyClass
class << self
include MyModule
end
end
MyClass.my_method # => "hello
I'm unsure why "include MyModule" needs to be in the singleton class in order to be called using just MyClass.
Why can't I go:
X = MyClass.new
X.my_method
What's the best way to add foreign keys to my existing tables in Rails with an underlying MySQL database? clearly the solution should be done in a migration, as I want this versioned. Otherwise I'd create the constraints myself.
I can't seem to find one, conducive response to they above. Again, the tables have already been created with previous migrations. I'm just going back now and adding referential integrity wherever it's applicable.
I'm attempting to interact with the Google contacts API through Rails via and oauth-plugin. I need to retrieve and update Google contacts. I know that the portablecontacts gem will retrieve contacts, but does not allow for adding or updating. I was wondering if anyone knew of a gem that will handle this type of interaction. If not what would be the best method to implement a gem that would make it easier to handle the responses.
Hi,
I'm trying to switch one of my websites into en-UK so that I get the correct date and currency formats etc...
I have found this yaml file:
http://github.com/mattetti/globalite/blob/master/lang/rails/en-UK.yml
Any ideas if there is a better one to use?
I also checked here but could not see it:
http://github.com/svenfuchs/rails-i18n/tree/master/rails/locale
Thanks,
Nick
Hi all,
I am looking to execute a password change over Net-ssh and this code seems to hang:
Net::SSH.start(server_ip, "user", :verbose => :debug ) do |session|
session.process.popen3("ls") do |input, output, error|
["old_pass","test", "test"].each do |x|
input.puts x
end
end
end
I know the connection works because using a simple exec I can get the output from ls on the remote server, but this hangs.
Any ideas?
The last message from debug is that the public key succeeded.
I'm trying to install a Rails app on a Cygwin Rails + WAMP MySQL setup, but rake trows an error :
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Of course, it's trying to connect to MySQL trought a Cygwin socket, and since there's no MySQL server running on Cygwin, it fails.
How do I get Rails to connect to WAMP's MySQL (perhaps through TCP/IP instead of a socket) ?
I have a 'validate_on_create' statement in one of my controllers that I would like all of my seed data to skip. What are some solutions so that the create statement in my seeds file skips this validation. My current solution is commenting out the validation each time I run rake db:seed. Anything a little more clever?
Looking on SO, I see that the preferred way to currency using RoR is using decimal(8,2) and to output them using number_to_currency();
I can get my numbers out of the DB, but I'm having issues on getting them in.
Inside my update action I have the following line:
if @non_labor_expense.update_attributes(params[:non_labor_expense])
puts YAML::dump(params)
The dump of params shows the correct value. xx,yyy.zz , but what gets stored in the DB is only xx.00
What do I need to do in order to take into account that there may be commas and a user may not enter .zz (the cents). Some regex and for comma? how would you handle the decimal if it were .2 versus .20 .
There has to be a builtin or at least a better way.
My Migration (I don't know if this helps):
class ChangeExpenseToDec < ActiveRecord::Migration
def self.up
change_column :non_labor_expenses, :amount, :decimal, :precision => 8, :scale => 2
end
def self.down
change_column :non_labor_expenses, :amount, :integer
end
end
Here's a story:
User A should be able to upload an image.
User A should be able to set a privacy. ("Public" or "Private").
User B should not be able to access "Private" images of User A.
I'm planning to user Paperclip for dealing with uploads.
If I store the images under "RAILS_ROOT/public/images", anyone who could guess the name of the files might access the files. (e.g., accessing http://example.com/public/images/uploads/john/family.png )
I need to show the images using img tags, so I cannot place a file except public.
How can I ensure that images of a user or group is not accessible by others?
With vim how do I to turn this:
t.string :crypted_password :null => false
t.string :password_salt, :null => false
into this:
t.string :crypted_password, :null => false
t.string :password_salt, :null => false
without manually adding the spaces to each line?
I'm working on a rails app to integrate with infusionsoft's xmlrpc api. Does anyone have any tips or pointers for integrating a system smoothly? What are best practices? How do you best re-factor code?
Thanks for any tips / ideas
I hope this question is clear enough -- if not let me know :)
What API would I use when I want to write a procedure at runtime and then just run it eventually at low priority while continuing to do the important stuff right now?
Example: link checker
1. I write a blog post with links represented by Link objects. I publish the post.
2. Eventually (at very low priority) the system gets around to fetching the URL of each Link object to make sure it's not broken and indicates that in a property of the Link object.
3. When a user visits my blog post, the render code that turns Link objects into HTML knows whether the links have been checked.
I'm assuming there's a very general purpose API for doing this kind of "eventually/low priority" stuff.
I'm working with some models where a lot of a given model's key attributes are actually stored in a submodel.
Example:
class WikiArticle
has_many :revisions
has_one :current_revision, :class_name => "Revision", :order => "created_at DESC"
end
class Revision
has_one :wiki_article
end
The Revision class has a ton of database fields, and the WikiArticle has very few. However, I often have to access a Revision's fields from the context of a WikiArticle. The most important case of this is probably on creating an article. I've been doing that with lots of methods that look like this, one for each field:
def description
if @description
@description
elsif current_revision
current_revision.description
else
""
end
end
def description=(string)
@description = string
end
And then on my save, I save @description into a new revision.
This whole thing reminds me a lot of attr_accessor, only it doesn't seem like I can get attr_accessor to do what I need. How can I define an attr_submodel_accessor such that I could just give field names and have it automatically create all those methods the way attr_accessor does?
Hi, I've read many posts about this issue but I never got this to work.
My model looks like this:
class Announcement < ActiveRecord::Base
validates_presence_of :title, :description
end
My controller's create method(only its relevant part) looks like this:
def create
respond_to do |format|
if @announcement.save
flash[:notice] = 'Announcement was successfully created.'
format.html { redirect_to(@announcement) }
format.xml { render :xml => @announcement, :status => :created, :location => @announcement }
else
@announcement = Announcement.new
@provinces = Province.all
@types = AnnouncementType.all
@categories = Tag.find_by_sql 'select * from tags where parent_id=0 order by name asc'
@subcategories= ''
format.html { render :action => "new" } #new_announcement_path
format.xml { render :xml => @announcement.errors, :status => :unprocessable_entity }
end
end
end
My form looks like this:
<% form_for(@announcement) do |f| %>
<%= error_messages_for 'announcement' %> <!--I've also treid f.error_messages-->
...
What am I doing wrong?
I have a bunch of strings that appear to have been double-escaped -- eg, I have
"\\014\"\\000\"\\016smoothing\"\\011mean\"\\022color\"\\011zero@\\016"
but I want
"\014"\000"\016smoothing"\011mean"\022color"\011zero@\016"
Is there a method I can use to unescape them? I imagine that I could make a regex to remove 1 backslash from every consecutive n backslashes, but I don't have a lot of regex experience and it seems there ought to be a "more elegant" way to do it.
For example, when I puts MyString it displays the output I'd like, but I don't know how I might capture that into a variable.
Thanks!
Edited to add context: I have this class that is being used to marshal / restore some stuff, but when I restore some old strings it spits out a type error which I've determined is because they weren't -- for some inexplicable reason -- stored as base64. They instead appear to be 'double-escaped', when I need them to be 'single-escaped' to get restored.
require 'base64'
class MarshaledStuff < ActiveRecord::Base
validates_presence_of :marshaled_obj
def contents
obj = self.marshaled_obj
return Marshal.restore(Base64.decode64(obj))
end
def contents=(newcontents)
self.marshaled_obj = Base64.encode64(Marshal.dump(newcontents))
end
end
Is this code threadsafe? It seems like it should be, because @myvar will never be assigned from multiple threads (assuming block completes in < 1s).
But do I need to be worried about a situation where the second block is trying to read @myvar as it's being written?
require 'rubygems'
require 'eventmachine'
@myvar = Time.now.to_i
EventMachine.run do
EventMachine.add_periodic_timer(1) do
EventMachine.defer do
@myvar = Time.now.to_i # some calculation and reassign
end
end
EventMachine.add_periodic_timer(0.5) do
puts @myvar
end
end