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 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.
I have a script where I need to take a user's password and then run a command line using it. I need to backslash all (could be more then one) non-alphanumeric characters in the password. I have tried several things at this point including the below but getting no where. This has to be easy, just missing it.
Tried these and several others:
password = password.gsub(/(\W)/, '\\1')
password = password.gsub(/(\W)/, '\\\1')
password = password.gsub(/(\W)/, '\\\\1')
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?
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.
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'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?
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.
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.
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?
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
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 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?
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
I would like to model a betting system relationship using the power of rails.
so lets start with doing something very simple modelling the relationship from a user to a bet.i would like to have a model bet with 2 primary keys.
here are my migrations
enter code here
class CreateBets < ActiveRecord::Migration
def self.up
create_table :bets do |t|
t.integer :user_1_id
t.integer :user_2_id
t.integer :amount
t.timestamps
end
end
def self.down
drop_table :bets
end
end
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :users
end
end
the models
enter code here
class Bet < ActiveRecord::Base
belongs_to :user_1,:class_name=:User
belongs_to :user_2,:class_name=:User
end
class User < ActiveRecord::Base
has_many :bets, :foreign_key =:user_1)
has_many :bets, :foreign_key =:user_2)
end
when i test here in the console my relationships I got an error
enter code here
u1=User.create :name="aa"
= #
u2=User.create :name="bb"
= #
b=Bet.create(:user_1=u1,:user_2=u2)
*****error*****
QUESTIONS:
1 How do I define the relationships between these tables correctly?
2 are there any conventions to name the attributes (ex:user_1_id...)
thank you for your help
Trying to convert output from a rest_client GET to the characters that are represented with escape sequences.
Input: ..."sub_id":"\u0d9c\u8138\u8134\u3f30\u8139\u2b71"...
(which I put in 'all_subs')
Match: m = /sub_id\"\:\"([^\"]+)\"/.match(all_subs.to_str) [1]
Print: puts m.force_encoding("UTF-8").unpack('U*').pack('U*')
But it just comes out the same way I put it in. ie, "\u0d9c\u8138\u8134\u3f30\u8139\u2b71"
However, if I convert a raw string of it:
puts "\u0d9c\u8138\u8134\u3f30\u8139\u2b71".unpack('U*').pack('U*')
The output is perfect as "??????"
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?
I'm working on creating a method that pads an array, and accepts 1. a desired value and 2. an optional string/integer value. Desired_size reflects the desired number of elements in the array. If a string/integer is passed in as the second value, this value is used to pad the array with extra elements. I understand there is a 'fill' method that can shortcut this - but that would be cheating for the homework I'm doing.
The issue: no matter what I do, only the original array is returned. I started here:
class Array
def pad(desired_size, value = nil)
desired_size >= self.length ? return self : (desired_size - self.length).times.do { |x| self << value }
end
end
test_array = [1, 2, 3]
test_array.pad(5)
From what I researched the issue seemed to be around trying to alter self's array, so I learned about .inject and gave that a whirl:
class Array
def pad(desired_size, value = nil)
if desired_size >= self.length
return self
else
(desired_size - self.length).times.inject { |array, x| array << value }
return array
end
end
end
test_array = [1, 2, 3]
test_array.pad(5)
The interwebs tell me the problem might be with any reference to self so I wiped that out altogether:
class Array
def pad(desired_size, value = nil)
array = []
self.each { |x| array << x }
if desired_size >= array.length
return array
else
(desired_size - array.length).times.inject { |array, x| array << value }
return array
end
end
end
test_array = [1, 2, 3]
test_array.pad(5)
I'm very new to classes and still trying to learn about them. Maybe I'm not even testing them the right way with my test_array? Otherwise, I think the issue is I get the method to recognize the desired_size value that's being passed in. I don't know where to go next. Any advice would be appreciated.
Thanks in advance for your time.
I've got a text area on a web site that should be limited in length.
I'm allowing users to enter 255 characters, and am enforcing that limit with a Rails validation:
validates_length_of :body, :maximum => 255
At the same time, I added a javascript char counter like you see on Twitter, to give feedback to the user on how many characters he has already used, and to disable the submit button when over length, and am getting that length in Javascript with a call like this:
element.length
Lastly, to enforce data integrity, in my Postgres database, I have created this field as a varchar(255) as a last line of defense.
Unfortunately, these methods of counting characters do not appear to be directly compatible. Javascript counts the best, in that it counts what users consider as number of characters where everything is a single character. Once the submission hits Rails, however, all of the carriage returns have been converted to \r\n, now taking up 2 characters worth of space, which makes a close call fail Rails validations. Even if I were to handcode a different length validation in Rails, it would still fail when it hits the database I think, though I haven't confirmed this yet.
What's the best way for me to make all this work the way the user would want?
Best Solution: an approach that would enable me to meet user expectations, where each character of any type is only one character. If this means increasing the length of the varchar database field, a user should not be able to sneakily send a hand-crafted post that creates a row with more than 255 letters.
Somewhat Acceptable Solution: a javascript change that enables the user to see the real character count, such that hitting return increments the counter 2 characters at a time, while properly handling all symbols that might have these strange behaviors.
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
I've been working with Rails for a while now and one thing I find myself constantly doing is checking to see if some attribute or object is nil in my view code before I display it. I'm starting to wonder if this is always the best idea.
My rationale so far has been that since my application(s) rely on user input unexpected things can occur. If I've learned one thing from programming in general it's that users inputting things the programmer didn't think of is one of the biggest sources of run-time errors. By checking for nil values I'm hoping to sidestep that and have my views gracefully handle the problem.
The thing is though I typically for various reasons have similar nil or invalid value checks in either my model or controller code. I wouldn't call it code duplication in the strictest sense, but it just doesn't seem very DRY. If I've already checked for nil objects in my controller is it okay if my view just assumes the object truly isn't nil? For attributes that can be nil that are displayed it makes sense to me to check every time, but for the objects themselves I'm not sure what is the best practice.
Here's a simplified, but typical example of what I'm talking about:
controller code
def show
@item = Item.find_by_id(params[:id])
@folders = Folder.find(:all, :order => 'display_order')
if @item == nil or @item.folder == nil
redirect_to(root_url) and return
end
end
view code
<% if @item != nil %>
display the item's attributes here
<% if @item.folder != nil %>
<%= link_to @item.folder.name, folder_path(@item.folder) %>
<% end %>
<% else %>
Oops! Looks like something went horribly wrong!
<% end %>
Is this a good idea or is it just silly?
Is there a better way to do this? (it looks clunky)
form_params = {}
form_params['tid'] = tid
form_params['qid'] = qid
form_params['pri'] = pri
form_params['sec'] = sec
form_params['to_u'] = to_u
form_params['to_d'] = to_d
form_params['from'] = from
form_params['wl'] = wl