I need to print Ruby on Rails complete url in my application. in details
with RAILS_ROOT I m getting a url like this
D:/projects/rails_app/projectname/data/default.jpg
But for my application I need a path like this
http://localhost:3000/data/default.jpg
Please help me to solve this issue. I am using Rails 2
Thanks
Today we use URI. Simply require the library and you will be able to parse your current dynamic and static URI any way you please. For example I have a function that can read URI parameters like so...
#{RAILS_ROOT}/app/helpers/application_helper.rb (The literal path string of the file depicted below)
def read_uri(parameter)
require 'uri'
#raw_uri = URI.parse(request.original_fullpath)
#uri_params_raw = #raw_uri.query
if #uri_params_raw =~ /\=/
#uri_vars = #uri_params_raw.split('=')
return #uri_vars[parameter]
end
return false
end
This should split all URI parameters into an array that gives the requested (numeric) "parameter".
I believe that simply the URI.parse(request.original_fullpath) should work for you.
I come from using a minimum of rails 4.2.6 with this method so, I hope it works for anyone who might view this later on. Oh, and just as a disclaimer: I wasn't so wise to rails at the time of posting this.
Related
I need to read the GBP rate from this javascript file: http://cdn.shopify.com/s/javascripts/currencies.js. I want to be able to get the js variable as JSON so that I can easily access the variable I need with its index. I tried a couple of ways as follows with eventually no success.
Way 1
Source: https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html
My code:
uri = URI('http://cdn.shopify.com/s/javascripts/currencies.js')
#response = Net::HTTP.get(uri) # => String
Result: I get the result as a string and reading the GBP rate from the string is difficult and probably not the correct way.
Way 2
Source: curl request in ruby
My Code:
url = 'http://cdn.shopify.com/s/javascripts/currencies.js'
mykey = 'demo'
uri = URI(url)
request = Net::HTTP::Get.new(uri.path)
request['Content-Type'] = 'application/xml'
request['Accept'] = 'application/xml'
request['X-OFFERSDB-API-KEY'] = mykey
#response = Net::HTTP.new(uri.host,uri.port) do |http|
http.request(request)
end
Result: This returns me Net::HTTP:0x007f2480874050 which looks like a memory address, definitely not what I want.
In addition, I've included require 'net/http', require 'json' in my controller in either case.
I am very new to Ruby and I don't know how to figure this out. So looking for someone who can help.
This is a bit of a weird request, IMO, but Rails can do it. Rails comes with a library called execjs automatically, which lets you run javascript from ruby. So, you have some javascript you want to run in that file, but you also want to return specific key from that javascript, so something like this should do it:
# Expanding upon 'Way 1', which got you the javascript as a string
uri = URI('http://cdn.shopify.com/s/javascripts/currencies.js')
response = Net::HTTP.get(uri)
gbp_rate = ExecJS.exec "#{response}; return Currency.rates.GBP;"
p gbp_rate # => 1.40045
I just want to reiterate (from their FAQ in the README) though:
Can ExecJS be used to sandbox scripts?
No, ExecJS shouldn't be used for any security related sandboxing. Since runtimes are automatically detected, each runtime has different sandboxing properties. You shouldn't use ExecJS.eval on any inputs you wouldn't feel comfortable Ruby eval()ing.
This file looks safe, but just keep it in mind, you are actually executing this javascript.
Personally, I would look to see if there's an API somewhere that can give you this value more easily, or if it doesn't change often (I have never used Shopify so don't know how much this changes) just hardcode it in the app as a config value and update it manually. Just feels cleaner, to me.
I'm a beginner in ruby. I want a ruby script to fetch every single link associated with that domain without using gems.
(e.x)
if i enter url as http://hsps.in
My Expected output is:
hsps.in/contacts
hsps.in/projects
hsps.in/blog ..etc
can anyone tell me how can i achieve this?
open-uri is part of the standard library, you'll need to install the nokogiri gem, it'll make things a lot easier
require 'open-uri'
require 'nokogiri'
url = 'http://hsps.in'
doc = Nokogiri::HTML(open(url))
links = doc.css('a')
links.each { |link| puts link['href'] }
RegExp is your friend :)
Maybe this gist would help you i created a while ago.
In Line 570 i use a Regexp to scan links:
toScan[:links] = toScan[:response].body.scan(/https?:\/\/[^:\s"'<>#\(\)\[\]\{\},;]+/mi)
and in Line 572 i use this Regexp to scan for intern links:
interneLinks = toScan[:response].body.scan(/href\s*=\s*['"]\/?[^\s:'"<>#\(\)\[\]\{\},;]+/im )
I also dont want to use gems and do it on my own. So i used a RegExp. With Regexpressions you can deal with Textpatterns. Its like a small language you can use to idetify text in a string (in your case urls). :) Maybe there is a better regexp for links (google could find them), but i want to deal with it on my own.
Hoptefully i could help you with that case.
In your controller action
arr = []
routes = %x[rake routes]
routes.split(' ').map{|rt| arr << rt if rt.count('/') > 0 && rt.count('#') == 0}
puts arr.uniq
require 'open-uri'
class PageLinks
attr_reader :page
include OpenURI
def initialize(url)
#page = open(url).readlines
end
def links
#page.grep(/href/)
end
end
url = 'http://www.hsps.in'
doc = PageLinks.new url
puts doc.links.inspect
As you said 'without using any gems' I will take it that includes Rails even though it is tagged as such.
This is not a 'clean' answer as it doesn't extract the values of the a tags href values. But it should demonstrate that it indeed can be done with no gems, only that which comes with Ruby.
is possible to generate an HTML page using Ruby on Rails framework without using a webserver?
I want do something like this:
html = RailsHTMLGenerator.generate('path/to/rails/root', '/posts/540')
puts html
The first parameter is the Rails.root, the second is the HTTP path, and the function return the HTML of that page as string.
Someone can tell me how to do this? Ty.
I've found a solution:
require '/path/to/application.rb'
app = APPName::Application.initialize!
session = ActionDispatch::Integration::Session.new(app)
session.get '/'
puts session.body
Well, you can do that from the Rails console
app.get '/foo'
This is how the console is initialized in case you want to try this approach:
https://github.com/rails/rails/blob/master/railties/lib/rails/commands/console.rb
I am getting the following error in one of my rails app [Ruby 1.8.7 + Rails 2.3.9]
A ArgumentError occurred in home#dashboard:
illegal character in key "dashboard_prod:views/reports/1050 - 097"
/opt/ruby-enterprise/lib/ruby/gems/1.8/gems/activesupport-2.3.9/lib/active_support/vendor/memcache-client-1.7.4/memcache.rb:643:in `get_server_for_key'
I googled and found that someone had similar problem at: http://www.coffeepowered.net/page/2/
on that page it is mentioned that, this should work:
class ActionController::Caching::Actions::ActionCachePath
def path
#cached_path ||= Digest::SHA1.hexdigest(#path)
end
end
But I am not sure where should I type this. So I have two questions:
How to solve problem at hand
Where should I write the code like the above where we are overriding some standard class or class defined in a Gem.
Any help would be appreciated.
I think the post you found is suggesting you create a monkey patch with that code. Create a file under Rails.root + 'lib/' with those contents, and make sure it loads after ActionController (which should be the default). The patch will override ActionController's default code.
You definitely want something like that--I always ensure my memcached keys are hashed. It makes them a little more difficult to debug, but it protects against problems like this and also key-length overflow errors when someone creates a key that's too long for memcached.
I'm messing around with rails 2.3 templates and want to be able to use the app name as a variable inside my template, so when I use...
rails appname -m path/to/template.rb
...I want to be able to access appname inside template.rb. Anyone know how to do this?
Thanks
I was looking for an answer to this question. unfortunately the answer above (#root) doesn't seem to work in Rails 3.
Here's the variables you can access in Rails 3 app templates (even easier):
#app_name
#app_path
Thanks for the answers. Mike Woodhouse, you were so close. Turns out, all you need to do to access the appname from inside your rails template is...
#root.split('/').last
The #root variable is the first thing created when initializing templates and is available inside your rails templates. RAILS_ROOT does not work.
In Rails 3, use the app_name attribute.
See the documentation for the Rails::Generators::AppGenerator.
I ran into a similar problem, none of the variables listed above were available to me in Rails 4. I found that #name was available while running
rails plugin new engines/dummy -m my_template.rb
There are other useful variables available from within the template. You can see for yourself and play around by utilizing pry. Inside my template I added
require 'pry'; binding.pry
and then ran ls to show a list of available instance variables
ls -i
instance variables:
#_initializer #app_path #behavior #destination_stack #extra_entries #name #output_buffer #shell
#_invocations #args #builder #dummy_path #gem_filter #options #rails_template #source_paths
#after_bundle_callbacks #author #camelized #email #in_group #original_name #shebang
There's probably a more straightforward way, but this seems to work:
RAILS_ROOT.split('/').last
EDIT: Bleah - this got voted down once, and the voter was right. If I'd read the question more carefully, I'd have noticed the 2.3 and template.rb elements. Apologies.
I suspect that RAILS_ROOT won't have been created at the point that you need the app name. Looking at ruby\lib\ruby\gems\1.8\gems\rails-2.2.2\bin\rails, however, almost the first thing that happens is this:
app_path = ARGV.first
It's used at the end of the script to allow a chdir and freeze to be done if needed - I didn't know I could insta-freeze at creation, so I learned something new at least. ARGV then gets used here:
Rails::Generator::Scripts::Generate.new.run(ARGV, :generator => 'app')
which quickly gets us to the place where ARGV is really handled:
rails-2.3.1\lib\rails_generator\scripts.rb
where I see
Rails::Generator::Base.instance(options[:generator], args, options).command(options[:command]).invoke!
Somewhere below here is probably where the templating gets handled. I'm afraid I'm at a very early stage with 2.3 and templating is an area that I haven't looked at yet.
Does that help any better than my first effort?
RAILS_ROOT will give you the absolute path to your root directory. Your app name will be the portion of the string after the final '/' which you can grab in any number of ways.
EDIT: Not quite enough to get the job done. Mike and Dan iron it out below.
I believe the preferred way now is to call Rails.root and no longer RAILS_ROOT. Apparently someone on planet rails has an aversion to uppercase or some similar important reason. As of 2.3.5 they both appear to work.
I was getting error
`template': undefined local variable or method `app_name'
ruby 1.9.2p290, rails 3.2.11, thor 0.18.0, Windows
but with rails 2.3 generator:
class DynanavGenerator < Rails::Generators::Base
(can't be sure whether this error happened under rails 3.0.9 or earlier)
changed class definition to be:
class DynanavGenerator < Rails::Generators::NamedBase
which then gave:
No value provided for required arguments 'name'
I then added a 'name' ("something" below):
rails generate dynanav something --force
which gave the original error, so I then added:
def app_name
#name.titleize
end
to the class and all was well.
As of Rails 4 (maybe earlier versions?), use Rails.application.class to get the application name. For example, if your app is named Fizzbuzz, here are a few ways you might access it:
rails(development)> Rails.application.class
=> Fizzbuzz::Application
rails(development)> Rails.application.class.name
=> "Fizzbuzz::Application"
rails(development)> Rails.application.class.parent
=> Fizzbuzz
rails(development)> Rails.application.class.parent.to_s
=> "Fizzbuzz"