How to render an image from a remote url - ruby-on-rails

I want to render a remote url (which is an image) as an image in an active admin show page, but those images are from a collection:
panel 'Media Items' do
render collection: record.chore.media_items.where(discrete_type: :image)
end
But I haven't been able to find anything that does both of these things.
The image url is stored as: chore.media_items.where(discrete_type: :image).first.url for example.

Use literal arbre syntax this way and it might work:
panel 'Media Items' do
record.chore.media_items.where(discrete_type: :image).each do |image|
img(:src => image.url, :style => 'height: 200px')
end
end
Instead of inline-styling, you could also pass a :class => 'yourCustomCssClass' to arbre's img dsl statement. Good luck!

Something like this maybe?
panel 'Media Items' do
record.chore.media_items.where(discrete_type: :image).each do |image|
image_tag image.url
end
end

Related

Using image_tag with srcset attribute?

I try to use an srcset attribute inside an image_tag but I can not make it work.
Im not sure if it is a syntax error or it generally does not work in an image_tag.
Is it possible to use a srcset attribute in an image_tag?
If yes, how?, and if not why not and is there a workaround?
<%= link_to(image_tag("logo.png", alt: "logo", :id => "logo"), root_path) %>
Instead of adding the image_tag to the link_to "name" option you can use open up block and pass your image there.
If you want to use a srcset attribute you could extend the functionality of image_tag by creating a helper:
def image_set_tag(source, srcset = {}, options = {})
srcset = srcset.map { |src, size| "#{path_to_image(src)} #{size}" }.join(', ')
image_tag(source, options.merge(srcset: srcset))
end
It joins each size by comma, so then you can do:
<%= link_to root_path do %>
<%= image_set_tag 'logo.jpg', {
'logo_640.jpg' => '640w',
'logo_1024.jpg' => '1024w',
'logo_1980.jpg' => '1980w'
}, sizes: '100vw', alt: 'logo', id: 'logo' %>
<% end %>
As you can see, the changes introduced in ActionView::Helpers::AssetTagHelper#image_tag in the 5.2.1 Rails version allows you to pass the srcset option, with a hash or an array of 2D arrays containing the different responsive versions of your image:
image_tag("icon.png", srcset: { "icon_2x.png" => "2x", "icon_4x.png" => "4x" })
# => <img src="/assets/icon.png" srcset="/assets/icon_2x.png 2x, /assets/icon_4x.png 4x">
image_tag("pic.jpg", srcset: [["pic_1024.jpg", "1024w"], ["pic_1980.jpg", "1980w"]], sizes: "100vw")
# => <img src="/assets/pic.jpg" srcset="/assets/pic_1024.jpg 1024w, /assets/pic_1980.jpg 1980w" sizes="100vw">
So, if you're using a more recent Rails version, you can just use image_tag instead of writing your own implementation.

how to embed raw html in active_admin formtastic

I'm trying to build a form, with formtastic, inside an active_admin model.
The problem is I need a certain script tag and other raw HTML stuff directly inside or around the form.
I'm doing it with the normal form block:
form do |f|
f.inputs :name => "User Details", :for => :user do |user_form|
user_form.input :first_name, :required => true
...
How do I embed a simple div tag right in between?
Or even a script tag?
I thought about using a render :partial, but I want to know if the above method is possible first. Thanks!
You can insert a div or javascript like this:
f.form_buffers.last << content_tag(:div, "Div content here")
f.form_buffers.last << javascript_tag("alert('hi');")
In the current ActiveAdmin the form_buffers is deprecated. Instead it's possible to do the following:
insert_tag(Arbre::HTML::Div) { content_tag(:span, "foo") }
Active admin created a DSL on top of Formtastic according to their docs
https://github.com/activeadmin/activeadmin/blob/master/docs/5-forms.md
So you can now do:
form do |f|
f.semantic_errors(*f.object.errors.keys)
import_errors = self.controller.instance_variable_get("#errors")
if import_errors.present?
ul class: 'errors' do
import_errors.each do |e|
li e
end
end
end
# ...
end

Make a Select Box that Calls a Method

I have a rails app with working reports that have tags. In the Report/Index.html.erb I want the user to be able to sort the reports by selecting a tag. They may only select one tag at a time so I feel that a select box would work best. I currently have this:
<%= select("preferences", :tag_with,
["Politics", "Technology", "Entertainment", "Sports", "Science", "Crime",
"Business", "Social", "Nature", "Other"], :prompt => "Filter Feed by:" )%>
I have a working preferences controller with a method call tag_with that updates the current tag. This code, however, only generates the select box. I want it to be that when the user selects one of the tags, it calls the tag_with method from the preferences controller.
I generated a series of link_to lines that complete the task, however I would really like a select box.
<%= link_to "Politics", :action => "tag_with", :tag => "Politics", :controller =>"preferences" %>
<%= link_to "Entertainment", :action => "tag_with", :tag => "Entertainment", :controller =>"preferences" %>
<%= link_to "Science", :action => "tag_with", :tag => "Science", :controller =>"preferences" %>
<%= link_to "Technology", :action => "tag_with", :tag => "Technology", :controller =>"preferences" %>
And so on for each tag. This works fine but is bulky and undesirable. Is there a way to do the same thing through a select box?
In your reports.js.coffee file, or whatever other js file you want.
jQuery ->
$('select#preferences').change ->
$.get 'preferences/tag_with',{ term: $('option:selected', this). val() }
Or, if you want to use regular javascript:
$(function(){
$('select#preferences').change( function() {
$.get('preferences/tag_with',{term: $('option:selected',this).val()});
});
});
A link is a GET request. The jQuery .change() method fires whenever someone makes a change. The $.get method sends a GET request to a URL and can pass data (the second argument). This data becomes your params hash, so in the example above you would get:
params[:term] #=> the value attribute of whatever option was selected by the user
See the jQuery docs on .change() and $.get() for more help.
Update
For this to refresh the page, the easiest thing would be to extract the table that you want changed into a partial, let's assume it's called _report.html.erb. The partial should look something like this:
<div id="report">
<%= render #report %>
</div>
*Note: render #report is just short for render :partial => 'report'. See http://guides.rubyonrails.org/layouts_and_rendering.html*
In your preferences controller, tag_with option you should be sure to set the #report object (or whatever else is delivering the data to your partial).
Then you should make a file called views/preferences/tag_with.js.erb and put something like this in it:
$('div#report').html('<%= escape_javascript( render #report ) %>');
This will update the report container with the new content.

How highlight found word with Sunspot?

I want to highlight found words in text, for example, as shown here.
As far as I know I must follow these steps:
1) In my model, I must add :stored => true option to the field which I want to highlight:
searchable do
text :title, :stored => true
text :description
end
2) In my controller, I have to declare which field I want highlighted:
def search
#search = Article.search do
keywords params[:search] do
highlight :title
end
end
end
3) In the view I'm not sure what to do, I tried this:
- #search.each_hit_with_result do |hit, result|
%p= link_to raw(hit_title(hit)), article_path(result)
It is what doing method hit_title:
def hit_title(hit)
if highlight = hit.highlight(:title)
highlight.format { |word| "<font color='green'>#{word}</font>" }
else
h(hit.result.title)
end
end
But it doesn't work as expected, it always highlights the first word of the title, even if the searched word is at the end of it.
Is there an easier way to do this?
I bumped into this looking for a solution to render highlights from sunspot search on rails view.
I didn't find much of a ready solution anywhere, so I used part of this post to make one of my one.
I am quite new to rails so this might not be fully the RoR way.
In my case, I did a full text search on two fields, call them notes and description.
In order to be able to render to html the highlights, I introduced a hash of values containing the id of the record, the name of the column and its highlighted value, adequately formatted. This allows me to highlight the search results on different fields.
entry.rb:
searchable do
text :description, :stored => true
text :notes, :stored => true
end
entries_controller.rb:
#search = Entry.search
if params[:search].nil? || params[:search].empty?
stext=''
else
stext=params[:search]
end
fulltext stext, :highlight => true
paginate(page: params[:page], :per_page => 10)
end
#entries=#search.results
#results=Hash.new
#search.hits.each do |hit|
hit.highlights(:description).each do |highlight|
id=hit.primary_key.to_s.to_sym
fr=highlight.format { |word| "<result>#{word}</result>" }
#results.merge!(id => ["description",fr])
end
hit.highlights(:notes).each do |highlight|
id=hit.primary_key.to_s.to_sym
fr=highlight.format { |word| "<result>#{word}</result>" }
#results.merge!(id => ["notes",fr])
end
end
and on the view, wherever I want to render any value of those, I do the following:
<% #entries.each do |f| %>
<% j=f[:id].to_s.to_sym %>
<% if !#results[j].nil? && #results[j][0]=="description" %>
<%= #results[j][1].html_safe %>
<% else %>
<%= f[:description] %>
<% end %>
[...] (likewise for notes)
<% end %>
Please, note I created a css definition for <result> markup to make the text notable.
Code looks good to me for highlighting the first matching word in the title, since I have similar code. Have you tried rebuilding your solr index and restarting the servers?
Also, can you try reverting your solrconfig.xml to its default values? Someone had a similar problem after modifying solrconfig.xml, Ref https://groups.google.com/forum/#!searchin/ruby-sunspot/highlight/ruby-sunspot/kHq0Dw35UWs/ANIUwERArTQJ
If you want to override the highlighting option in solrconfig.xml, search for max_snippets on this site http://outoftime.github.io/ . You may want to try options like
highlight :title, :max_snippets => 3, :fragment_size => 0 # 0 is infinite
Are you using substring search? I've got the same problem here and realized that enabling substring match by following sunspot wiki tutorial led to the problem.

Rails/ajax - whitespace and request.raw_post

I am starting to learn Ajax with rails.
I have a catalog index page with a text_field_tag querying db if it finds similar "section" results.
Index.html.erb
<h1>Catalogs</h1>
<label>Search by Section:</label>
<%=text_field_tag :section %>
<%= observe_field(:section,
:frequency=> 0.1,
:update=> "article_list",
:url=>{ :action => :get_article_list }) %>
<div id="article_list"></div>
Catalogs_controller.rb
def index
end
def get_article_list
#section = request.raw_post.split(/&/).first
#catalogList = "<ol>"
Catalog.find(:all, :conditions => ["section = ?", #section]).each do |catalog|
#catalogList += "<li>" + catalog.title + "</li>"
end
#catalogList += "</ol>"
render :text => #catalogList
end
Question:
request.raw_post renders something like:
xml&authenticity_token=tgtxV3knlPvrJqT9qazs4BIcKYeFy2hGDIrQxVUTvFM%3D
so I use
request.raw_post.split(/&/).first
to get the section query ("xml"). It works, however how can I do if the query have a whitespace. (like "Open Source") In fact, I have Open Source sections in my db, but request.raw_post.split(/&/).first renders Open%20Source. How can I manage this? Did I have to use a full text search engine to achieve it or there is another way?
Thanks a lot for your explanation!
Look over your logs, in them you will see the post and the params being passed. You should not need to do your own query-string splitting. You should be able to use params[:section] to get the post data.
As your comment implies, there's something missing. Your observe_field needs to tell the Rails helper what to do. Check out: http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/observe_field. Anyhow, you'll want to do something like:
observe_field(... # lots of parameters
:with => 'section'
)
And that should give you params[:section].

Resources