Ruby on Rails API for beginner json response - ruby-on-rails

I am new to ruby on rails. I apologize early if this question might be dumb... but I can't figure this out and the tutorials I've seen is making this simple task confusing. Or I am just not understanding what I am missing or what to do... if a step by step tutorial may help, thanks!
My task to make a rails api that you can pass JSON to via postman/DH.
The payload will be {"value": "foo"}. A '200 (OK)' Response with payload of {"value":"bar"}
No database needed, just a controller that takes in a payload and gives back a response.
This is what I do know...
What I do know is how to create a rails api by "rails new testrails --api"
Then going to my 'gemfile' and installing some kind of json to gems.
Then... I mess with the 'route.rb' file in config and the controller in'apps'.
I get lost here on what I need to do with the route file and controller...
What ever steps come next.

Step 1: install Rails 5
$ gem install rails
Step 2: create an API-only Rails application
$ rails new my_app --api
Step 3: integrate rack-cors
Add gem 'rack-cors' at the bottom of your $RAILS_ROOT/Gemfile ($RAILS_ROOT stands for the root directory of your rails app), then
$ bundle install
Then add these lines to your $RAILS_ROOT/config/application.rb, inside the class definition
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :patch, :put, :delete, :options]
end
end
Step 4: generate a controller
$ rails g controller foo
Add an action to the FooController (in file $RAILS_ROOT/controllers/foo_controller.rb)
def create
foo = params[:foo]
# Do whatever you want with foo
render json: {value: 'bar'}
end
Step 5: add a route
Modify the file $RAILS_ROOT/config/routes.rb, add
post '/foo' => 'foo#index'
in the block
Step 6: start rails server
$ rails s
That's all. Now you can send POST requests to http://localhost:3000/foo and see what happens.

Related

Non specific MVC framework ruby gems and example code to Rails framework

I have been learning Ruby on Rails, but I still have issues when it comes to Ruby gems with examples that are irb based and not Rails or Sinatra framework based. I am trying to implement the Block.io Bitcoin API functionality. But the code I find is Ruby only, so I am not sure where to create a config file for the API Key and also whether I need to create a controller to make this work in the views for Rails.
The gem and examples are on: https://github.com/BlockIo/gem-block-io
I installed this gem via bundle install on Rails
gem install block_io -v=1.0.6
The Ruby example show the following:
>> require 'block_io'
>> BlockIo.set_options :api_key=> 'API KEY', :pin => 'SECRET PIN', :version => 2
In Rails which config file would I enter the above api_key and pin?
In the example they show the code to get your address as follows:
BlockIo.get_my_address
Do I need to create a function in a controller such as:
def address
#my_address = BlockIo.get_my_addresses
end
and in the view use:
<%= #my_address %>
I need some guidance with regards to the above, any comment or assistance will be greatly appreciated.
require 'block_io' can go into Gemfile like gem 'block_io'. Rails/bundler will require it automaticaly for you as long as the gem name is also the file name you want to require from this gem.
BlockIo.set_options :api_key=> 'API KEY', :pin => 'SECRET PIN', :version => 2 can be put into an initilizer like config/initializers/block_io.rb. This way set_options is called only once when Rails starts a server or console or runner.
Put it like this into the file config/initializers/block_io.rb
BlockIo.set_options :api_key=> ENV['BLOCK_IO_API_KEY'], :pin => ENV['BLOCK_IO_PIN'], :version => 2
With the environment variables in use you don't commit any secret into your repo.
Now you should be able to call BlockIo.get_my_address within any action.

how to retrieve data from Bigcommerce using Rails application?

I am trying to connect a Rails application with the Bigcommerce API but I can't and I don't know why.
I made the next:
Add 'gem bigcommerce' to my gem file
Execute 'bundle install'
Put the code behind in the ApplicationController index
def index
api = Bigcommerce::Api.new({
:store_url => "http://mystore.mybigcommerce.com",
:username => "user",
:api_key => "3a0ce...[my api key]"
})
puts api.time
end
Stop and Start Rails server
I received an error saying 'undefined method `time' for #'
Does any body could tell me what I am doing wrong and how to configure Bigcommerce in a Rails app? I found the official documentation, but it's not very clear for me.
Thanks in advance
Have you added require at the beggining of your ApplicationController file?
require 'bigcommerce'

undefined method 'patch' - routing error

I am beginner in Rails & MVC development, and need help with the below:
I am doing the example in http://edgeguides.rubyonrails.org/getting_started.html
In "5.12 Updating Posts", we are asked to add the following to our config/routes.rb:
patch "posts/:id" => "posts#update"
If I do that, and run rake routes, I am getting the below error:
undefined method `patch' for #<ActionDispatch::Routing::Mapper:0x390f078>
I get the same error when I go to - http://localhost:3000/posts/1
This is the line in edit.html.erb :
<%= form_for :post, url: { action: :update, id: #post.id }, method: :patch do |f| %>
I have Rails 3.2.1.
Environment:
I am doing this in Windows 7. I installed Rails via railsinstaller.org. Browsers - Chrome, Firefox
patch is only available in Rails master branch.
Here is the related pull request: https://github.com/rails/rails/issues/348
Here is the blog article explaining the reasoning: http://weblog.rubyonrails.org/2012/2/25/edge-rails-patch-is-the-new-primary-http-method-for-updates/
Here is another great summary: http://blog.remarkablelabs.com/2012/12/http-patch-verb-rails-4-countdown-to-2013
Among other things, you need to point to the git repo in your Gemfile to use edge rails on an already-existing project.
gem 'rails', :git => 'git://github.com/rails/rails.git'
For now you should just use PUT instead of PATCH. Even when 4.0 comes out, PUT isn't going anywhere.
fwiw, I backported the HTTP PATCH verb work for Rails 3.2 https://gist.github.com/bf4/8940203

RoR: Sinatra producing error "uninitialized constant"

I'm new to Ruby on Rails (formerly and currently PHP expert) so forgive my ignorance but I'm trying to get Sinatra working as middleware to redirect some old urls since I tried the gem rack-rewrite and couldn't get that to work either.
I am using code samples from ASCIIcast so in my routes.rb I have the following:
root :to => HomeApp
(^ I'm redirecting the root only for testing)
In my lib folder I have home_app.rb
class HomeApp < Sinatra::Base
get "/" do
"Hello from Sinatra"
end
end
When I start the server (or if its already running) it produces the error:
routes.rb:10: uninitialized constant HomeApp
Which seems that it just isn't aware of the lib/home_app.rb file.
I have included Sinatra in my Gemfile and ran bundle install and confirms it is included.
I just want to reroute old urls from my old site to my new ruby app but can't get any of this middleware/rack stuff working. All documentation assumes you aren't a total newb or is for RoR pre-3.0.
You don't need to use Sinatra if you want to redirect some URLs. You can use the new redirect method. See the Rails Dispatch article.
match "/stories/:year/:month/:day/:name" => redirect("/%{name}")
constraints :user_agent => /iPhone/, :subdomain => /^(?!i\.)/ do
match "*path" => redirect {|params, req| "http://i.myapp.com/#{req.fullpath}" }
end
In your specific case, the problem is that the HomeApp class is not loaded. Either add the /lib folder to your load path changing application.rb
config.autoload_paths += %W( #{config.root}/lib )
or require the file.

Sinatra app as Rails 3 subpath

I'm trying to get a sinatra app as a subpath in my rails 3 app.
Specifically, the resque queuing system has a sinatra based web interface that I would like to have accessible through /resque on my usual rails app.
You can see the project here: http://github.com/defunkt/resque
I found some people talking about adding a rackup file and doing this sort of thing:
run Rack::URLMap.new( \
"/" => ActionController::Dispatcher.new,
"/resque" => Resque::Server.new
)
But I don't really know where to put that or how to make it run. My deployment is with passenger, but it would me nice to also have it running when I run 'rails server' too. Any suggestions?
--edit--
I've made some progress by putting the following in config/routes.rb:
match '/resque(/:page)', :to => Rack::URLMap.new("/resque" => Resque::Server.new)
Which seems to work pretty well, however it loses the public folder, (which is defined within the gem I guess), and as a result, there is no styling information, nor images.
You can setup any rack endpoint as a route in rails 3. This guide by wycats goes over what you are looking for and many of the other things you can do in rails3:
http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/
For example:
class HomeApp < Sinatra::Base
get "/" do
"Hello World!"
end
end
Basecamp::Application.routes do
match "/home", :to => HomeApp
end
Yehuda (/Scott S)'s solution doesn't work for me with Rails 3.0.4 and Sinatra 1.2.1... setting :anchor => false in the matcher is the key:
# in routes.rb
match "/blog" => MySinatraBlogApp, :anchor => false
# Sinatra app
class MySinatraBlogApp < Sinatra::Base
# this now will match /blog/archives
get "/archives" do
"my old posts"
end
end
(answer c/o Michael Raidel - http://inductor.induktiv.at/blog/2010/05/23/mount-rack-apps-in-rails-3/)

Resources