Make user-inputted url into external link in rails - ruby

I want users to be able to enter a url and then put a link to that url in my view.
Valid inputs could be e.x. https://www.google.com/path, http://www.google.com, www.google.com
Is there are standard rails way to 1) validate that input is a valid url format and 2) convert that third format to http://www.google.com in my views so the external link works?
I don't want to re-invent the wheel if I can avoid it.

Check this out:
validates_format_of :website, :with => URI::regexp(%w(http https))
Source: http://intridea.com/2009/2/18/quick-tip-url-validation-in-rails?blog=company
To format a URL that is missing the protocol (http or https), I would do a before_save hook that prepends it if it's missing:
before_save :format_url
...
def format_url
self.website = "http://#{self.website}" unless self.website[/^https?/]
end

The Domainatrix gem comes highly recommended for validating URLs:
https://github.com/pauldix/domainatrix

Related

Unable to route in ruby on rails as I encounter specific error

I'm using rails 5.0 and I get the
PostsController#index is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []
NOTE! For XHR/Ajax or API requests while trying to input my url/posts.
my routing.rb file is below:
Rails.application.routes.draw do
get 'posts/index' => 'posts#index'
resources: posts
end
my posts_controller.rb looks like below:
class PostsController < ApplicationController
def index
end
end
I want to know specifically what I'm doing wrong. I've just started to learning Ruby on Rails.
Template is missing. You need to create a file ie index.html.erb under directory /app/views/posts/index.html
GET profiles/employees- Should display all the employees
GET profiles/employees/:id should display a specfic employee
GET profiles/donors - Should display all the donors
GET profiles/donors/:id - Should display a specfic donor
routes in ruby on rails behave in the same way as href tag in rails
we use get for link and if we want toi perform any action on button then w e have to use button.
if you have any doubt let me know in detail.
for more details refer this
http://guides.rubyonrails.org/routing.html
if we write only localhost:3000/employees then bydefault our application will redirect to index page.
The issue is template missing you are missing the template file index.html.erb
I have notice that on your snapshot you named the template file as index.html.erb.txt
remove the .txt and rename to index.html.erb Then it should work
Also you don't need to declare the routes as
get 'posts/index' => 'posts#index'
Just declare the resources: posts is enough. You may check the routes using the rake routes command on your rails console
Rename the file index.html.erb.txt to index.html.erb

URL Rewrite Ruby on Rails

We have a Redmine installation on an old server and moved it to a new one with a new domain. Problem is, we need to redirect urls from the old domain to the new one. I really don't have much knowledge about ruby. I was thinking redirecting URLs on this one is as easy as some rewrite rules with .htaccess but I found it different. I've read some answers here redirect but can't figure out where to put those codes.
The scenario should be like:
from http://www.old-domain.com:3000/issues/3456
should be redirected to http://www.new-domain.com:3000/issues/3456
Can anyone help me how to do this? Or if you have better idea how to achieve this?
I'm planning on reading some ruby guides for the meantime.
Thanks guys!
Update:
I managed to create a simple redirect by doing the following:
I created a controller redirect_controller.rb:
class RedirectController < ApplicationController
before_filter :show
def show
redirect_to "http://www.new-domain.com:3000/", :status => :moved_permanently, :notice => "Notice: A redirect!!!"
end
end
And added this to routes.rb:
map.connect '/', :controller => 'redirect'
But I only managed to redirect the page after a successful login. How can I redirect all pages to the new one retaining parameters such as /issues/3456 if there are any?
You can go to your application.rb file (I found it better than place the redirection in the application controller), which is loaded to start all the rails and all engines. The key here is to use
head :moved_permanently, :location => "http://www.newdomain.com/"
To call that you can wrap it in a method I found in a blog. I added some comment
def perm_redirect_to(options)
url = case options
when String # if you pass a string url, which is your case
options
else
url_for(options) # if you pass some more complex option hash in
# `options`, which doesn't seem to be your case
end
head :moved_permanently, :location => url
end
You can call this method passing your url perm_redirect_to(your_new_url)!

How can I render an image with Padrino?

I need to create image files on-the-fly in my controller with RMagick and send them to browser. Looks like it's very simple, but I can't find a way. I've tried just simply render them, but it fails due to data is binary. I've also tried to use send_data, but Padrino says it doesn't know about such method.
So, what have I missed? How can I solve this problem?
Researching how to send files through Padrino controller I've found this question and it helps me to reach my goal.
The send_data method is a Sinatra request-method which has been removed in the version 1.0: https://github.com/sinatra/sinatra/blob/1.0/CHANGES#L108
I'm using the Padrino version 0.10.7 and my action have became into this:
get :screenshot, :provides => :jpg do
...
File.open("path/to/file", "r").readlines
end
according to sinatra api you don't need this anymore.
get :image, with: id, provides: :png do
img = Image.find(params[:id])
img.binary_data_or_so
end
basically is the same of:
get '/send_binarydata' do
content_type 'image/png'
\x01\x02\x03
end

CouchDB: weird query_parse_error with curl, not with Ruby

I'm hosting my Couch instance on iriscouch.com and doing some testing with a simple Sinatra app, using CouchRest Model.
Here's a simple model I'm using:
class User < CouchRest::Model::Base
property :first_name, String
property :last_name, String
timestamps!
design do
view :by_first_name
end
end
I'm successfully creating new users with:
User.create(:first_name => "Stonewall", :last_name => "Jackson")
Executing User.by_first_name.all results in this HTTP request:
http://test_admin:pwd#testytest.iriscouch.com:80/blt/_design/User/_view/by_first_name?include_docs=true&reduce=false
"Accept"=>"application/json"
"Accept-Encoding"=>"gzip, deflate"
"Content-Type"=>"application/json"
This is executed by RestClient, via CouchRest. No problems there.
But when I try to curlthis URL, I get complaints from Couch about the include_docs parameter:
{"error":"query_parse_error","reason":"Query parameter `include_docs` is invalid for reduce views."}
I'd like to understand what's going on here. Why is include_docsa problem only when using curl?
One difference is that your URL now contains a question mark. If you don't protect the URL in the shell, it will be interpreted as a special character.
If you want a simpler way to test your services, you can use RESTClient instead of curl.

Ruby open-uri open method loses file extension opening images

I'm using ruby 1.9.2 along with Rails 3.1.4 and Paperclip 2.4.5.
My issue is trying to save a paperclip attachment from a URI loses the file extension and saves the file without one resulting in issues with things like fancybox that require an extension.
Some example code:
uri = "http://featherfiles.aviary.com/2012-06-13/bbe5f0de1/0c5a672b88ea47ecb4631ac173e27430.png"
open(uri)
#=> #<File:/var/folders/zc/d69gxhzx10x_bvjrkqgyjgxr0000gn/T/open-uri20120613-27204-i6cldv>
Because there is no extension on the temp file paperclip is saving the file without one resulting in issues.
Has anyone run into this issue? I've seen multiple answers about using paperclip to store images from a URI but none seem to address the same problem we're running
Don't use the temporary file! It's there as a placeholder as the file is read from the port, and should be considered a private resource for OpenURI. Instead, use open(url).read and work with the resulting content by saving it.
Do something like:
require 'uri'
require 'open-uri'
url = 'http://www.iana.org/domains/example/index.html'
filename = File.basename(URI.parse(url).path)
File.open(filename, 'wb') do |fo|
fo.write(open(url).read)
end
Temporarily spooling to disk during an operation, especially a network operation, is common. Once the file's content has been accumulated, then it is available to be passed off to the app. read is blocking, so your code will stop there until the file is returned to you. Then you can play with it.
Extension isn't important for temporary file, but if you want use this file in code or save to another place. You can do it:
temp_file = open(params[:url])
def temp_file.original_filename; File.basename(base_uri.path); end
Now, you can save this temporary file to permanent space or use it in code; Original filename will be used automatically.
Im not sure if this will help in your case, but I was noticing similar issues in my project.
The issue turned out to be not caused by Paperclip nor open-uri, but the receiver of the paperclip file (in my case Spree Commerce). Check that you are assigning the paperclip object to the right object, and that it is being interpreted correctly.
The fix that worked for me was to change:
#product.images << Spree::Image.create({
:attachment => open(image_url)
}, :without_protection => true)
to
#product.master.images << Spree::Image.create({
:attachment => open(image_url)
}, :without_protection => true)
Good luck with your issue
Have you inclued the :extension in your path/url option?
For example:
has_attached_file :image,
...
:url => '/images/highlights/:id_partition/:style_:id.:extension',
:path => ':rails_root/files/images/highlights/:id_partition/:style_:id.:extension'
This will probably solve your problem.
You can force an extension there, but I don't think that's recommended.
Update – Paperclip can do this on its own!
Posted by Aditya Sanghi (thanks a lot!):
current_comments.pictures.create!(file: URI.parse(image_url))
Although keep in mind, that you still need to handle 500, 404, etc
errors (Paperclip can raise them).
Thanks to: https://mensfeld.pl/2013/12/rails-paperclip-open-uri-downloading-files-from-the-internet-and-saving-them-with-paperclip/
Yes, it is a problem but we can get around this with fancybox.
In the link tag(for image) add :type => 'image'
- #images.each do |image|
= link_to image_tag(image.attachment.url), image.attachment.url, class: "fancybox", type: 'image'
By specifying 'type', Fancybox overrides the type as image
https://groups.google.com/forum/?fromgroups=#!topic/fancybox/QgjquBCLynU

Resources