Rendering an image from the Unsplash API in Rails - ruby-on-rails

I have extensively researched this matter both on Stack Overflow and Google but found nothing conclusive. Since I'm completely new to the concept of API usage within Rails I have to ask for some advice.
I have followed the procedure from the github page
I have included the Unsplash helper in application_helper.rb as follows
def show_photo
Unsplash::Photo.find("tAKXap853rY")
end
and simply added
<%= image_tag show_photo %>
in my view.
This returns an object (So connectivity is good)
<img src="/images/#<Unsplash::Photo:0x007fc4b2f953c0>" alt="#
<unsplash::photo:0x007fc4b2f953c0>">
I'm aware that Rails is looking for a picture in the assets/images folder
How do I parse the inbound JSON and render it in my Rails view?

You can access to the urls key within the OpenStruct attributes in the Photo object that includes the raw, full, regular, small and thumb sizes, also as keys.
So, just to test you could use the raw one, like:
<%= image_tag Unsplash::Photo.find('tAKXap853rY')[:urls][:raw] %>
Or I think you could modify your method to accept one parameter which is the size key of the image, like:
module ApplicationHelper
def show_photo(size)
Unsplash::Photo.find("tAKXap853rY")[:urls][size.to_sym]
end
end
Then:
<%= show_photo('raw') %> # 'full', 'regular', etc ...

further to this solution I am trying to display the photographer's name by using the user.name method.
In the console I can get the following :
photo = Unsplash::Photo.find("tAKXap853rY")
photo.user.name
will return
=> "Alejandro Escamilla".
But in RAILS :
def show_photo(size)
#photo =Unsplash::Photo.find("tAKXap853rY")[:urls][size.to_sym]
end
just trying to display the name in my view like:
<%= #photo.user.name %> will return "user undefined method".
The .user.name is accessible in the console but not in rails! What have I missed? Thanks

Related

Rendering polymorphic object in Rails

For people that only want the question, here it is :
Is there a way to specify the folder to look in when you call render on an object? I don't want to specify the view, only the folder to look in.
And for people that want context :
I am working on an activity stream system (something that looks like google+/facebook).
I have "Activities", which are exactly like google+ feeds (or facebook, or whatever!). So, I have a simple loop that display each activities, which are bound to one of the following object (polymorphic) : User, Group, Comment, Note.
In my view that render an activity (views/activities/_activity.html.erb), I have
<%= render activity.object %>
where activity.object is a reference to the bound object (User, Group, Note, Comment). If it's a user, it goes to views/users/_user.html.erb and renders it. For a group, views/groups/_group.html.erb.
That works just fine. However, I come to the point where the rendering of a group in my activities should not be the same rendering as in the group list page. Is there a way to specify the folder to look in when you call render on an object? So that my :
<%= render activity.object %>
would become :
<%= render activity.object, :folder => 'views/activities/' %>
Note that I don't want to specify which view directly, as I don't want to do a case for each of the possible types of objects (User, Group, Note, Comment) in the activity. I want to to have the same behaviour as of right now, which means if it finds a views/activities/_user.html.erb, it would load any user in the activities with that view instead of the one in the views/users/_user.html.erb.
Thanks
I'm not aware of any folder type option, but when I do this I usually do:
<%= render "activities/#{activity.object.class.name.underscore}" %>
That would give you similar behaviour.
EDIT A good point below by Dominic, if your classes are nested in namespaces, you will have to include the appropriate structure.
i.e.
module Foo
class Bar < ActiveRecord::Base
end
end
# class.name is Foo::Bar, underscored is 'foo/bar'
<%= render "activities/#{activity.object_type.underscore}" %>
# will be in
activities/foo/_bar.html
In current Rails (3.2.9), you can define a to_partial_path method on your model to tell it where to look.
For example, you can do:
class User
def to_partial_path; "user"; end
end
Rails will then look for _user.html.erb relative to the view from which you're calling render.
My own approach, which I extracted in polymorphic_render gem - to add suffixes for special partials, but store that partial in resource folders.
In your case views/users/_user.html.erb will have very common user representation (which probably used in users list rendering), but views/users/_user_activity.html.erb will render special partial for user activity.
And inserting that partials is very simple, just <%= polymorphic_render activity.object, :activity %>

How do I output to website instead of console for debugging in Rails?

Well the title explains pretty much everything.
I want to use something like
p something
And be able to see the output in the website, just for the sake of debugging.
I suspect you're coming from PHP, because this is a very PHP-esque thing to want to do. Standard output isn't sent to the browser in Rails, something PHP developers take for granted.
If you want to see something in browser, you need to render it.
From a view you can use the debug helper to "vardump" a value:
<%= debug something %>
From a controller you can quickly see the value of a variable using render :inline => p(something) or render :inline => something.inspect. Make sure you return afterwards or otherwise prevent yourself from reaching a second render call.
You should get used tailing your log files, and making use of the Rails logger.
I would suggest piggy-backing off of the Rails flash maps. In a controller, use the following:
flash[:log] = "<li>Log: #{log_info}</li>"
Then in your view (possibly in your layout) use:
<% if !flash[:log].blank? && RAILS_ENV != 'production' %>
<ul class="logs">
<%= flash[:log] %>
</ul>
<% end %>
That should put it out on your page!
You can also put the following in ApplicationController
def log(msg)
flash[:log] ||= ""
flash[:log] += "<li>#{Time.new.to_s} - #{msg}</li>"
end
Then simply call from any controller:
log("Hi stackoverflow.")
Or from any view:
#controller.log("Hi there, you!")

How to create an atom feed in Rails 3?

I'm trying to set up a simple atom feed from my Posts model and I'm running into translation problems between rails 2 and rails 3.
I tried to accomplish this task with two steps:
Added the <%= auto_discovery_link_tag(:atom) %> to my /views/layouts/application.html.erb file.
Created a /views/posts/index.atom.builder file. The file contains:
atom_feed do |feed|
feed.title("Daily Deal")
feed.updated(#posts.first.created_at)
#posts.each do |post|
feed.entry(post) do |entry|
entry.title(post.title)
entry.content(post.body, :type => 'html')
entry.author { |author| author.name("Justin Zollars")}
end
end
end
I see the RSS link in my browser, but the link opens with an error:
Too many redirects occurred trying to open
“feed:http://localhost:3000/posts”.
This might occur if you open a page
that is redirected to open another
page which then is redirected to open
the original page.
Where have I gone wrong?
Try specifying a path to the feed:
<%= auto_discovery_link_tag(:atom, posts_path(:atom)) %>
Maybe you need to specify the actual feed address?
auto_discovery_link_tag :atom, "http://mysite.com/posts.atom"
If you're using FeedBurner, you'll want to use that address instead.
Also, do you have some kind of before_filter blocking the access to that page?

Template path in Rails 3

Let's say, I connected the route / to WelcomeController's index action.
Inside of the index.html.erb-Template I want to display the path of the template from Rails.root upwards, ie.
<h1> We are rendering: <%= how_do_i_do_this? %></h1>
to render to
<h1> We are rendering: app/views/presentation/index.html.erb</h1>
In Rails 2 I could access template.path, but this doesn't work anymore
Any ideas?
Because of how template rendering works in Rails, you will now be able to use __FILE__ for this instead. This works for me:
<%= __FILE__.gsub(Rails.root.to_s, "") %>
There may be a better way to do this however, but I couldn't find it when I went looking.
Ryan's answer works. If you also want to put your method in a helper, use Kernel#caller. Here is a method I'm using to do something similar:
def has_page_comment? code = nil
if code.nil?
# grab caller file, sanitize
code = caller.first.split(':').first.gsub(Rails.root.to_s,'').gsub('.html.erb','')
end
...
end

Basecamp API Rails

I was wondering if someone could do me massive favour..
I really don't understand how to make use of APIs - so I was wondering if, using Basecamp as an example, someone could talk me though the basics.
So far I have an application with a dashboard controller/view, I have put basecamp.rb into my /lib directory, added the following to my application_controller:
def basecamp_connect
Basecamp.establish_connection!('XXXXXX.basecamphq.com', 'USER', 'PASS', false)
#basecamp = Basecamp.new
end
Obviously changing the required parts to my credentials.
Next up I have added the following to my dashboard_controller:
def index
Basecamp::TodoList.find(:all)
end
Next I presume I have to somehow list the Todos on the dashboard using some sort of loop.
Am I doing the right thing, if so - how on earth do I display all the todo items and if not - what am I doing wrong/missing.
It doesn't have to be todos, anything from Basecamp or any other popular API service would be a good start. It's just that I happen to have a basecamp account!
Thanks,
Danny
Your view expects to have some variables defined. You can loop through those variables and display their content as you want.
So you could do, in your action :
def index
#list = Basecamp::TodoList.find(:all)
end
Then in your view you have access to the #list variable and you can to the following :
<ul>
<% #list.each do |item| %>
<li><%= item.to_json</li>
<% end %>
</ul>
Replacing the json dump by the elements as you wish to display them of course.
You might want to read the rails guides to get a lot more of informations.

Resources