I have a method in my rails app that saves the image from an og:image tag url.
def photo_from_url(url)
if !Nokogiri::HTML(open(url)).css("meta[property='og:image']").blank?
photo_url = Nokogiri::HTML(open(url)).css("meta[property='og:image']").first.attributes["content"]
self.photo = URI.parse(photo_url)
self.save
end
end
This works in most cases, except when the image url happens to include a number that start with 0, such as http://ad009cdnb.website.com/rest-of-url
In these cases, I get an illegal octal digit error.
How can I prevent the method from thinking that any numbers starting with zero are base-8?
This is not a answer. Sorry for use the system wrongly. Can't find out how to put a string with HTTP without change it in a link as comment.
URI.parse works fine:
URI.parse("http://ad009cdnb.website.com/rest-of-url").to_s
=> "http://ad009cdnb.website.com/rest-of-url"
as everyone said, we really need a stacktrace or something to help you. And most likely you will want to save the URL as a string, not as an object on the database.
Hi guys I posted this question, but I can no longer reproduce the question.
As this is no longer an issue, I think the best course of action is to close this question. However, I see that some people have been voted up for their comments (They make good points like saving as a string instead of an object). Will they be discredited if the questions is closed?
I'm grateful for everyone's input, and don't want to upset anyone. What is SO protocol for a situation like this?
Related
I really don't know how to ask for what I'm asking for ... I'd google if I knew what I was looking for!
So, I have a set of carrierwave versions of images names image00, image01, image02 etc up to image25 stored as:
#photo.main.image00, #photo.main.image01 etc ...
I want to be able to use a controller to post these images out. But I have no idea how to string the request together. I've got objective-c, javascript, Ruby and a host of other languages fighting for space in my head, and Ruby seems to have lost out!
I wish to be able to make a call such as:
#photopiece = Base64.strict_encode64(File.read(#photos.main.imageXX.current_path))
but have no idea how to replace the XX with a digit and still have the file encoded.
I tried:
imagestring = "#photos.main.image#{sendPiece}.current_path"
and then
#photopiece = Base64.strict_encode(File.read(imagestring))
But that did nothing ... I could almost hear the compiler laughing at me (such is my paranoia now!)
So, how do I get the photo names to appear in the form:
#photos.main.imageXX.current_path
such that they can get parsed by strict_encode?
Thanks in advance for help! And reading my ramblings ...
PS. Apologies for the really bad heading! Please change it if you know what I'm asking for!
You can use public_send
piece = #photos.main.public_send("image#{sendPiece}")
#photopiece = Base64.strict_encode64(File.read(piece.current_path))
Maybe, it would be more secure than silly eval(params..):
number_is_safe = !!Float(sendPiece) rescue false
if number_is_safe
path = eval "#photos.main.image#{sendPiece}.current_path"
#photopiece = Base64.strict_encode(File.read(path))
end
jvnill propose much better solution:
piece = #photos.main.public_send("image#{sendPiece}")
#photopiece = Base64.strict_encode64(File.read(piece.current_path))
I am trying to use Regex to get the company name out of the email address. I am splitting the email two times. Is there a better solution for this?
c = "user#company_name.com"
(c.split("#").last).split(".").first
Another solution given.
str = "user#company_name.com"[/[^#]+(?=\.)/]
See working demo
Answer to the question in the post (before it was edited)
Judging from your code, it seems like you want to extract the top level domain (although it contradicts with the title, which does not make sense). Assuming so, this will give you the top level domain.
"user#company_name.com"[/[^.]+\z/]
# => "com"
Solution to a different problem that the OP additionally mentions in the comment to this answer
"user#company_name.com"[/(?<=#)[^.]+/]
# => "company_name"
This will give you company name.
(.*)#(\w+)\.(.*)
I have a website which is www.abrisud.com. This website has 7 domain names (one for each language): abrisud.com, abrisud.it, abrisud.de, etc... and abrisud-enclosure.co.uk.
The problem is on the last one: I am losing my session on every single request. Each Time I load a page I have a different session ID. On the other domains everything is working just fine.
The website is running ruby 1.8.7 and rails 3.0.0.
I am really convinced that the problem comes from the "-" in the domain name but I just can't find anything (or almost anything) on the subject through the web.
Hopefully I am being clear enough, if not just tell me.
Here is the answer :
From Module ActionDispatch::Http::URL (Rails 3.0.x), be sure to read the comments ;-)
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org".
# You can specify a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
def domain(tld_length = 1)
return nil unless named_host?(host)
host.split('.').last(1 + tld_length).join('.')
end
Well, calling the domain method with the appropriate _tld_lenght_ argument did not play the trick, the request.domain (abrisud-enclosure.co.uk) was good, but not the session_domain (still co.uk).
So I had to add the following lines as a before filter to my application_controller :
def set_session_domain
request.session_options[:domain] = request.domain
end
If you have a better solution I am open to it as I think this is a really dirty fix.
Thanks
I have taken a peak at your site, the cookie is set with: domain=co.uk;path=/
So the problem is within your rails stack and not the browser(s) - time to do some debugging :-)
I periodically fetch the latest tweets with a certain hashtag and save them locally. In order to prevent saving duplicates, I use the method below. Unfortunately, it does not seem to be working... so what's wrong with this code:
def remove_duplicates
before = #tweets.size
#tweets.delete_if {|tweet| !((Tweet.all :conditions => { :twitter_id => tweet.twitter_id}).empty?) }
duplicates = before - #tweets.size
puts "#{duplicates} duplicates found"
end
Where #tweets is an array of Tweet objects fetched from twitter. I'd appreciate any solution that works and especially one that might be more elegant...
you can validate_uniqueness_of :twitter_id in the Tweet model (where this code should be). This will cause duplicates to fail to save.
Since it sounds like you're using the Twitter search API, a better solution is to use the since_id parameter. Keep track of the last twitter status id you got from your previous query and use that as the since_id parameter on your next query.
More information is available at Twitter Search API Method: search
array.uniq!
Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
Ok, turns out the problem was a bit of different nature: When looking closer into it, I found out that multipe Tweets were saved with the twitter_id 2147483647... This is the upper limit for integer fields :)
Changing the field to bigint solved the problem. It took me very long to figure out since MySQL did silently fail and just reverted to the maximum value as long as it could. (until I added the unique index). I quickly tried it out with postgres, which returned a nice "Integer out of range" error, which then pointed me to the real cause of the problem here.
Thanks Ben for the validation and indexing tips, as they lead to much cleaner code now!
I've got a nice little "photos" class that has attached images. When I go to the page to sort the photos' order, it iterates though each photo, sets the new "sort" value, and saves it. All good so far.
Problem is, I've noticed this behavior is fairly slow. Turns out, attachment_fu reloads the thumbnail on every save - regardless of whether or not there's new image data to work with.
Obviously this system has been well-thought-out, so I'm only left to assume that a provision exists for this situation. How do I tell attachment_fu not to regenerate the thumbnails when it's not appropriate?
Thanks, --Matchu
Edit: I just remembered that, for this particular situation, I can use update_attribute to dodge all the validations and other callbacks. However, this isn't really a viable answer to the whole big scenario. What am I missing?
Went in and hacked attachment_fu a bit, and rewrote the save_attachment? behavior. Pretty much, I added some new conditions: in addition to a temp file existing, one of the following must be true:
No file for the image already exists (using the full_filename attribute).
The image data was explicitly updated using the uploaded_data= method.
The image is a thumbnail.
It passes all three test cases - new photo uploads, edit photo images, and editing non-image photo data - but I haven't really tested this out in the wild just yet. I'll probably have to make a few fixes; we'll see what happens.
The only moderately useful thread I've seen on this topic is here:
http://groups.google.com/group/rubyonrails-talk/browse_thread/thread/709d97e06b373786
I think Matchu's solution is probably the correct one with a quick review of the attachment_fu code. I'd love it if Matchu could share a patch or a snippet of his modified save_attachment? method. I'm about to dig into this on my own, since this has become a problem for me and it'll probably be less work than replacing attachment_fu entirely...
Update
With Matchu's outline, I came up with a short (if inelegant) solution that seems to work after light testing.
I modifed save_attachment? in attachment_fu/attachment_fu.rb:
def save_attachment?
return false unless (thumbnail || !full_filename || #active_upload) #added
File.file?(temp_path.to_s)
end
... to check the conditions Matchu laid out. I couldn't come up with an elegant way to tell whether data had been passed along to the uploaded_data= setter method (if anyone has a better way to do this, I'm all ears; I'm still a ruby/rails noob) so I also added a line to uploaded_data= to set the global variable #active_upload:
def uploaded_data=(file_data)
return nil if file_data.nil? || file_data.size == 0
self.content_type = file_data.content_type
self.filename = file_data.original_filename if respond_to?(:filename)
#active_upload=true # added
if file_data.is_a?(StringIO)
file_data.rewind
self.temp_data = file_data.read
else
self.temp_path = file_data
end
end
Hope that helps, and if anyone has a more elegant way to handle what I did there with the global variable, I'd love to hear it.