I am trying to choose an image randomly from a sub directory inside my /app/assets/images directory using the Dir.glob() command, and then display it with an image_tag. Somehow I can't get it to work.
Here's my code:
- #badges = Dir.glob("app/assets/images/badges/*")
= image_tag #badges.sample
Which produces the following error:
ActionController::RoutingError (No route matches [GET] "/assets/app/assets/images/badges/produce.png"):
As you can see the asset pipeline is inserting an "/assets" in front of the directory. Alright Rails, I'll meet you halfway here. So next I try removing /app/assets from the query path to make it work and get the following result:
- #badges = Dir.glob("images/badges/*")
= image_tag #badges.sample
ActionController::RoutingError (No route matches [GET] "/assets"):
What am I doing wrong here? Thanks in advance for your help!
Dir.glob is going to return images with a relative path, so your produce.png file will be returned as:
`app/assets/images/badges/produce.png`
However, you need to pass only the badges/produce.png part to image_tag. You need to remove the stuff before this:
= image_tag #badges.sample.gsub("app/assets/images/", "")
You may want to stick this in a helper instead:
def random_badge
badges = Dir.glob("app/assets/images/badges/*")
image_tag badges.sample.gsub("app/assets/images/", "")
end
and then in your view:
= random_badge
Related
I have a Sinatra template file, which sends a POST request to the route /en/signup (en is the locale).
I need to extract the en from /en/signup. I tried to use request.path in the following code, but contains only /signup, not /en/signup. The log file shows that /en/signup was called.
What construct can I use in the route post '/signup' in order to get /en/signup?
Wake up, Neo.
From route file:
before '/:locale/*' do
I18n.locale = params[:locale]
request.path_info = '/' + params[:splat ][0]
end
That solved my problem: redirect to('/' + I18n.locale.to_s + '/signup-success').
If you can use java:
var url = document.URL;
var pieces = url.split("/");
Then simply split where and when you need to. The variable pieces is an array. For further splitting use pieces = pieces[1 (or others) ].split("/ (or others ");
I hope this helps!
Hello Sir if you use php try the code below. it will get the full path of the url for instance /example/en/signup.
$_SERVER['REQUEST_URI']
In Addition you can get including the http host (localhost) try the code below
$output = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
echo $output;
I currently have no index views (app/views/mycontroller/index.html.erb), but would like to specify a default view if the user just types in: localhost:3000/mycontroller
Very new to RoR. My current config/routes.rb:
MyTestApp::Application.routes.draw do
get "team/thatguy"
get "home/about"
root :to => "home#about"
end
In my controller I've been playing around with redirects, but the desired solution is to only show the smaller uri localhost:3000/mycontroller.
app/controllers/home_controller.rb:
class HomeController < ApplicationController
def index
render "home/about"
end
def about
#title = "My Title"
end
end
Ok, assume you want to render a contact page when you access localhost:3000/mycontroller
What you want to do is:
Create a controller (C of MVC) with a contact action.
$ rails generate controller StaticPages contact
Excuting this code in your console creates some directories and files:
static_pages_contoller.rb with a contact action.
static_pages directory under the app/views directory with a view template called contact.html.erb
and you may have get 'static_pages/contact' in your config/routes.rb
Modify your routes:
Now you have access to the contact template with: localhost:3000/static_pages/contact
So to change the path, add a line to the routes.rb: match '/mycontroller', 'static_pages#contact', via: 'get'
Then you'll get your desired results.
I might be wrong, the whole process and details are here: http://ruby.railstutorial.org/ruby-on-rails-tutorial-book
I am using the ruby Dir method to get all the filenames within a directory. Like this:
dir_files = Dir["/Users/AM/Desktop/07/week1/dailies/regionals/*.csv"]
This gives me an array with each element listed below:
/Users/AM/Desktop/07/week1/dailies/regionals/ch002.csv
/Users/AM/Desktop/07/week1/dailies/regionals/ch014.csv
/Users/AM/Desktop/07/week1/dailies/regionals/ch90.csv
/Users/AM/Desktop/07/week1/dailies/regionals/ch112.csv
/Users/AM/Desktop/07/week1/dailies/regionals/ch234.csv
Im trying to extract just the part of the above strings that matches: "regionals/*.csv"
How do I do that in Ruby?
The following didn't work
#files_array.each do |f|
f = f.split("/").match(/*.csv/)
i = f.include?(".csv")
puts "#{i.inspect}"
#self.process_file(f[i])
end
Whats a clever way of doing this? I intend to pass the returned string of each filename to a helper method for processing. But as you can see all the csv files are located in a different directory as my executing script.
My script thats executing this is located at
/Users/AM/Desktop/07/week1/dailies/myScript.rb
Thanks
This will always post back the final directory and file name, regardless of the file pattern:
#files_array.map { |f| f.split("/")[-2..-1].join("/") }
#=> ["regionals/ch002.csv", "regionals/ch014.csv", "regionals/ch90.csv", "regionals/ch112.csv", "regionals/ch234.csv"]
This gives you the desired values :)
dir_files.map {|path| path[/regionals\/.*.csv/]}
#=> ["regionals/ch002.csv", "regionals/ch014.csv", "regionals/ch90.csv", "regionals/ch112.csv", "regionals/ch234.csv"]
I tried meta_search, but after adding "include MetaSearch::Searches::ActiveRecord" into my model, it raised an error as "undefined method `joins_values'" when run "MyModel.search(params[:search])"
I think I dont need full text, so I think following gems are not suitable for my project now::
mongoid_fulltext
mongoid-sphinx
sunspot_mongoid
mongoid_search
I tried a old gem named scoped-search
I can make it work for example:
get :search do
#search = Notification.scoped_search(params[:search]
search_scope = #search.scoped
defaul_scope = current_user.notifications
result_scope = search_scope.merge defaul_scope
#notifications = result_scope
render 'notifications/search'
end
but it will be allow to call any scopes in my model.
Is there any "best practice" for doing this job ?
If you want limit the scope you want use on your scoped_search you can filter your params[:search] like :
def limit_scope_search
params[:search].select{|k,v| [:my_scope, :other_scope_authorized].include?(k) }
end
I have ~ 500+ flag images that I previously kept in public/images/flags/ and public/images/flags_small/. For each country in my Country model, I store the :iso_code, which is the same as the name of the flag image that corresponds to it. For example, mx.png is the name of the Mexican flag because mx is the two-letter ISO code for Mexico.
I previously had a helper method that would return the html to display the image based on the iso code of the country and whether I wanted the large or small flag.
With Rails 3.1, to comply with the asset pipeline, I'm under the impression that those images should go into the app/assets/images folder. Following from this:
Can I maintain the subfolders therein?
How do I use image_tag to display the appropriate images?
Edit: solution
The answer below was correct, but I didn't want to type that much code each time,so I created two helper methods:
def flag(country)
image_tag('/assets/flags/' + country.iso_code.downcase + '.png')
end
def small_flag(country)
image_tag('/assets/flag_small/' + country.iso_code.downcase + '.png')
end
Yes, you can
For example: <%= image_tag 'flags/uk.gif' %>
As a quick solution to load images dynamically for Rails 5 (from a resource other than assets pipeline), imagine you have a controller called car.
add a new action (e.g. our action is called image) in your controller;
def image
path = "C:/pics/.../test.jpg" # just a sample path to test
send_file path, :content_type => 'image/jpg', :disposition => 'inline'
end
add the new route to your action in routes.rb;
get '/img', to: "car#image"
and finally in your ERB file, create an image tag with;
<div>
<%= image_tag url_for(:controller => "home", :action => "image") %>
</div>
This is just to test the basics and you can make it parametrized (to load the image based on id, name, etc.)