Coder Social home page Coder Social logo

rocket_pants's People

Contributors

ahegyi avatar bantic avatar damirsvrtan avatar davidpdrsn avatar ekampf avatar fabn avatar fredwu avatar fsmanuel avatar fvioz avatar joergschiller avatar johnrees avatar justinjones avatar keithpitt avatar kevinjalbert avatar knu avatar levibuzolic avatar manuelmeurer avatar mbhnyc avatar michaelachrisco avatar monfresh avatar oakho avatar paxer avatar sj26 avatar sutto avatar xunker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rocket_pants's Issues

Mixing test helpers into Minitest?

All-

A couple things, I'm using Minitest on my latest project (seeing as it's the new default and all!) and am having a couple issues:

  1. I get an undefined method default_version' for AssetsController:Class` error, the controller test looks like this:
require "minitest_helper"

describe AssetsController do
  default_version 1

  let(:user) { create :user }

  it "should get index" do
    skip "must fix assigning file to uploader"
    a = create(:asset, user_id: user.id, file: "#{Rails.root}/lib/assets/test.mov" )
    get :index
    assert_response :success
  end
end

Here's my minitest_helper:

ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)

require "minitest/autorun"
require "minitest/rails"
require "minitest/rails/capybara"
require "rocket_pants/test_helper"
require "factory_girl"
require "carrierwave/test/matchers"

class MiniTest::Rails::ActiveSupport::TestCase
  include FactoryGirl::Syntax::Methods
  include CarrierWave::Test::Matchers
  include RocketPants::TestHelper,    :type => :controller
  include RocketPants::RSpecMatchers,    :type => :controller
end

class MiniTest::Rails::ActionController::TestCase
  include ActiveSupport::Testing::SetupAndTeardown
  include Rails.application.routes.url_helpers
  include Capybara::DSL
  include Capybara::RSpecMatchers
end

MiniTest::Rails.override_testunit!

DatabaseCleaner.strategy = :truncation

Not that this even runs - I get a TypeError: include': wrong argument type Hash (expected Module) (TypeError)

Anyway, has anyone gotten this configured correctly for Minitest, or does some work need to be done?

Displaying validation errors in client application forms

Hi Darcy,
Thanks for the handy gem. I've got one question I couldn't find an easy solution for, maybe you can help me out with this.
I have two separate applications (one for regular users, another administration) with a single user base, the admin app acting as a web service for the user app (the API client). I need to display validation errors on login/registration forms in the user app. Since the user app is not backed by a DB, things become a little unwieldy on the client side since I don't get any of the ActiveModel convenience stuff out of the box when using RP clients instead of ActiveRecord models. Here's what I had to do to get the errors displayed properly.

I defined base classes for clients and the hashes they encapsulate (they are later used to trick form builder into binding input fields to attributes). The encapsulated 'model' has to have a model_name method and an ActiveModel error hash, otherwise simple_form_for will die with exceptions I've spent about 3 hours debugging :(

module Api
  class Base < RocketPants::Client
    version 1
    base_uri Rails.application.config.api.base_uri

    attr_accessor :auth_token

    def base_request_options
      session[:user] ? { headers: { 'X-AUTH' => session[:user][:auth_token] } } : {}
    end
  end

  class ModelBase < APISmith::Smash
    property :id
    property :errors

    def self.model_name
      ActiveModel::Name.new(self)
    end

    def to_key
      id
    end

    def populate_errors_from(error_hash)
      self.errors = ActiveModel::Errors.new(self)

      error_hash.each do |attr, msgs|
        msgs.each { |msg| self.errors.add(attr, msg) }
      end
    end
  end
end

Now, a client for the User model:

class Api::UserClient < Api::Base
  class User < Api::ModelBase
    property :first_name
    property :last_name
    property :email
    property :password
    property :password_confirmation
    property :provider_id
  end

  attr_reader :user

  def initialize(*args)
    @user = User.new(*args)
    super(*args)
  end

  def find(id)
    get "/user", extra_query: { id: id }
  end

  def save
    post "/users", extra_query: { user: @user }
  end
end

The corresponding controller on the client application side is below. It rescues the invalid record exception raised by the client base code, populates the error hash and re-renders the action with the form.

class UsersController < ApplicationController
  skip_before_filter :authenticate, only: [:new, :create]

  def create
    @user_client = Api::UserClient.new(params[:user])

    respond_to do |format|
      begin
        @user_client.save
      rescue RocketPants::InvalidResource => e
        format.html do
          @user = @user_client.user
          @user.populate_errors_from(e.errors)
          render action: :new
        end
      else
        format.html { redirect_to root_path, notice: t("signed_up_but_not_approved") }
      end
    end
  end
end

This works, but feels way too convoluted for a simple scenario like this. I feel there should be an easier way to do this.
I guess this post is a little too long, but anyway I'd be grateful if you could read through this and point me in the right direction here. I hope I've explained everything clear enough.

Thanks.

Example of Namespace with Controllers with Rocket Pants

I'm new to Rails and Ruby and was wondering if you could give an example for this statement:

"And in the case of multiple versions, I strongly encourage namespaces the controllers inside modules."

Your original example:

class UsersController < RocketPants::Base
  version 1 # A single version
  # or...
  version 2..3 # 2-3 support this controller
end

Then in routes:

api :versions => 1..3 do
  get 'x', :to => 'test#item'
end

How would these change? What would the folder structure look like??

- app
  - controllers
     - api
       - v1

Thanks.

Pagination setup

Hey guys-

Something dumb here I'm sure, but it's eluded me for long enough, so I'm turning on pagination support, and have tried BOTH kaminari and will_paginate, but in either case, the pagination section of my response is null.

Here's the controller action:

  def index
    paginated Session.where(user_id: @user.id).page(parmams[:page]).as_json(include: [ :takes, :project ], methods: :all_members)
  end

The response comes back correctly, with 10 results (which i've set on the model), and when i add a page parameter to the request, i get the correct objects back, but I still get:

"pagination": null

Is there another step to the configuration that I'm missing? This is on rails 3.2.11 with edge rocket_pants, and most uptodate will_paginate. I was getting an identical issue with kaminari.

Token authentication via request header support?

Is it possible to use token authentication where the token is passed via the request headers in a RocketPants::Client? I'm using this example: http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html where I have the following in a before_filter on my server:

authenticate_or_request_with_http_token do |token, options|
  token == [THE TOKEN]
end

However, I cannot figure out how to send this authorization token in the header of the client request, as in the test example in the Rails docs where it has:

get(
  "/notes/1.xml", nil,
  :authorization => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
)

Using the api_smith docs, I've tried using all of the following in my Client, thinking one of these would work but they don't:

def base_request_options
  {:authorization => ActionController::HttpAuthentication::Token.encode_credentials([THE TOKEN])}
end

...

def users
   add_request_options!( {:authorization => ActionController::HttpAuthentication::Token.encode_credentials([THE TOKEN])} )
   get 'users', :transformer => User
end

...

def users
  get 'users', :extra_request => {:authorization => ActionController::HttpAuthentication::Token.encode_credentials([THE TOKEN])}, :transformer => User
end

In fact, I've even put in all of these AND all of the query and body variations all at once and it clearly isn't working. Any thoughts?

EDIT

BTW, if I use this on my server in the before filter:

render :status => :forbidden, :file => "#{Rails.root}/public/403.html" unless params[:auth_token] == [THE TOKEN]

And this in my client:

def base_query_options
  {:auth_token => [THE TOKEN]}
end

Then everything works fine to authenticate via the query string. I just really want to know if there's a way to pass the token via an authorization request header instead.

Thanks!

Using Rocket Pants within an engine

Hello friends,

Do not get too excited for this, as we're only just testing the waters. I've been experimenting with an api re-do of Spree this morning/afternoon on my fork of Spree's api branch.

I think this is a little different from traditional applications usage of the API, as it's going to be an engine that can be mounted, rather than an API provided by an application.

So with this experimentation, I attempted to create a simple ProductsController and of course I wrote a test for that.

The problem is when I run the test, it gives me a HUGE response object with this error:

["{\"error\":\"invalid_version\",\"error_description\":\"This action is not available in the given version of the api.\"}"]

But I'm so positive that I've defined the right routes, the controller correctly and the test... so I don't know what I could be possibly doing wrong.

Hints/Tips/Tricks appreciated.

HTTP Basic Auth

Rails 3.2, when I try to use HTTP Basic Auth, I've got

undefined method authenticate_or_request_with_http_basic

Rendering views

Are you actively preventing views from being rendered? I would think that including ActionController::Rendering and it's ilk in my ApplicationController would do the job.

Here's my code and exception.

class Api::V1::ApplicationController < RocketPants::Base
  include ActionController::Rendering
  version 1
end
class Api::V1::DevicesController < Api::V1::ApplicationController
  def create
    # ...
    render :create
  end
Missing template api/v1/devices/create, api/v1/application/create with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :jbuilder, :coffee, :haml]}. Searched in:

It looks like the search paths for the templates are getting wiped out somewhere. I've been digging but haven't found anything.

Do you have any insight on this issue?

How to Use ActiveRecord Errors

Hi Sutto,

Forgive my n00bness, but I'm a bit confused about this part of the documentation:

Built in ActiveRecord Errors

Out of the box, Rocket Pants will automatically map the following to built in errors and rescue them as appropriate.

ActiveRecord::RecordNotFound into RocketPants::NotFound
ActiveRecord::RecordNotSaved into RocketPants::InvalidResource (with no validation messages).
ActiveRecord::RecordInvalid into RocketPants::InvalidResource (with messages in the "messages" key of the JSON).

If I want to return ActiveRecord errors caused from @resource.save, how would I do that? How would I use this "ActiveRecord::RecordNotSaved into RocketPants::InvalidResource" for error! ?

Thanks in advance,
Jeff

Problem with version prefixes

Version prefixes work fine for routing, but they always cause an invalid version error, in every case, every time. It doesn't appear that there's anything that translates the prefixed version into an integer that can be handled at the controller level.

I've hacked together an override of the version method to strip the prefix, but this leads to prefixes in code and in the routing. There should be a way to configure a prefix at a higher level, and have that apply to both routing and the version method in the controller.

Open to suggestions so I can try it myself.

uninitialized constant RocketPants::RSpecMatchers::APISmith

Given the following spec:

require 'spec_helper'

describe Api::RootController do

  describe "GET #index" do

    it "respond with a funny message" do
      get :index, :version => 1

      response.should have_exposed("foo")
    end

  end

end

I get the following error:

F

Failures:

  1) Api::RootController GET #index respond with a funny message
     Failure/Error: response.should have_exposed("foo")
     NameError:
       uninitialized constant RocketPants::RSpecMatchers::APISmith
     # ./spec/controllers/api/root_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

Finished in 0.0129 seconds
1 example, 1 failure

Kaminari support

Rocket Pants doesn't currently support Kaminari. Attempting to use Kaminari-paginated model with paginated results in an undefined method previous_page error. I believe that will_paginate provides these method, but Kaminari does not.

Using and customizing errors in the model

I'm trying to use the bad_request error (in a Model) with custom metadata, like this:

error! :bad_request, :metadata => {:specific_reason => "radius must be a number"}

but it's telling me error! is undefined.
I'm able to use raise RocketPants::BadRequest instead, but I can't figure out how to add the metadata option to it. Is it possible? If so, how? If not, is there a way to make error! available to the Model Class?

Thanks!

Feature request: drop restriction on version names

I see in the routing code

raise ArgumentError, "Got invalid version: '#{version}'" unless version =~ /\A\d+\Z/

I'd like to have non-integer version names.

I have 2 use cases where I want to have non-integer api versions

  • I don't like leaking my versions to the outside world. I often use dates or codenames for versions. e.g. v20130701 (which I could still use as a big number). Kind of like how Heroku differentiates their stack versions (cedar vs bamboo)
  • I do few integrations with big partners and I'd like to have them on a custom version/endpoint. If my big partners are BigCorp and Acme, I can build separate versions for each of them, but share everything underneath -- just the path is different initially (were the version method in the controller to accept an array of version names). Then, down the road, if one of them wants a change, I can customize just for one of them because they're already on their own version without affecting the other.

JSONP support

Hi,

Are you planning to add support for jsonp?

Would be interesting to add an option in render_json options hash called 'callback' and get this from params.

RocketPants 2.x Planning

The "What"

This issue hopefully will help solicit and facilitate a discussion around any proposed changes being incorporated into the 2.x release.

The "Why"

While working with rocket_pants I noticed the lack of support for some semi-standardized (well nothing in API land is truly standard) like content-type based routing and hypermedia-based pagination to name a few. Out of this I released the rocket_shorts gem (see jsmestad/rocket_shorts) that provided this varied functionality through a series of shims and overrides.

After releasing it, I solicited @Sutto for some feedback on the direction, which quickly turned into proposition to merge that work into "the next major version of rocket_pants"

The "Where"

Drafted Proposal: 2.0 Planning

Support for Active Model Serializers

Given that rocket pants avoids views, serializers seem the best way to format data. rocket pants currently does not easily support Active Model Serializers, but it seems like it should look for them when available. I'll be providing a pull request for an example implementation shortly.

Token authentication support in RocketPants::Base?

Similarly to #26, but on the server-side:

Does RocketPants work with token-based authentication on the server?

I tried putting this in my controller:

before_filter do
  authenticate_or_request_with_http_token do |token, options|
    error! :unauthenticated unless token == SEKRIT
  end
end

but if a token isn't passed then I get 500s because RocketPants doesn't provide render.

EDIT:
Simply using authenticate_with_http_token doesn't work either, because having no token skips the authentication block altogether...

Spec helper support for prefixes?

I'm sure this is on the list, but just in case, it doesn't seem possible to use a version prefix (even an optional one in a controller spec, I get a missing route error.

Or is there a way to construct the version that works?

Routing: rocket pants not respecting `shallow` option?

Hey guys-

So here's s routes snippet I have in my app:

  api :version => 1 do
    resources :sessions do
      resources :takes,           only:   [ :create, :update ], shallow: true
    end
  end

here are the routes this outputs:

session_takes POST   /:version/sessions/:session_id/takes(.:format)       takes#create {:version=>/(1)/, :format=>"json"}
take PUT    /takes/:id(.:format)        takes#update {:version=>/(1)/, :format=>"json"}

Odd right? So the path for session_takes is correct, but the path for "take" doesn't have /:version in front of it, which is incorrect.

Has anyone seen this before?

Can't make rocket pants work with doorkeeper

When trying to use doorkeeper along with rocket_pants, as soon as I change my controller to inherit from rocket pants base controller, I'm getting the following error: undefined method `doorkeeper_for'

Devise Integation

Hi,

Thank you so much for reading this. I'm really interested in using Rocketpants, but am having trouble integrating devise into it. Could someone give a pointer?

Thanks in advance,
Jeff

Warden/Devise Integration

So, I'd like to authenticate my API againsts users in my database. Auth is controlled via devise. What would be the best way to accomplish this?

How to get send_file working?

Hey guys-

Hoping this is an easy one.. the APIs I'm building requires a facility to upload and download files, but i'm having trouble getting send_file to work (not including the right stuff).

Or is there a better way to support file sending?

Right now, i'm including

  include ActionController::Instrumentation
  include ActionController::Streaming
  include ActiveSupport::Notifications

In my controller (which inherits from RB)

But running my download method results in this error:

{"error":"system","error_description":"super: no superclass method `send_file' for #<AssetsController:0x007f89f42a5eb0>"}

I see the super call in instrumentation.rb, but not sure what else needs to be included.

Ideas? And curious how I'd have debugged this on my own..

Etags for collections

Before hacking away at the code working around purpose built functionality, I was wondering what's the reason behind collections not using an ETag.

I would have thought letting a reverse proxy do the work of cache validation of a resource (even if it happens to be a collection) would be preferential over doing that work in rack middleware.

And is there anything wrong with having a Cache-Control: max-age on a single resource?

I would also have thought letting reverse proxies, or client caches (depending on the public/private nature of the Cache-Control) do the work of serving the resource would also be preferential.

I'd like to modify the code to have more control over the caching options and make use of HTTP caching (as I understand it), but am happy to be convinced otherwise if I can reap some other hidden benefits (I'm yet to understand) by working with the current code instead of against it. :)

(Also, there's a link in the README to Rack::Cache FAQ, but for some reason that no longer exists.)

Rails 4 : no implicit conversion of Symbol into Integer in specs

I recently migrated an application to Rails 4 beta and all of my controllers specs broke up with this odd error.

After some investigation I noticed that ActionController::TestCase::Behavior.process method signature changed in Rails 4 while it seems RocketPants overrides this method in RocketPants::TestCase.

So, I made some changes to the RocketPants::TestCase.process method to make it compliant with the one in Rails 4 and now all my specs pass successfully.

You can find Rails 4 changes here : https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/test_case.rb#L497

Using rocket_pants with backbone.js

Hi,

rocket_pants seems really nice and I would like to use it with backbone.js.

Backbone.js doesn't like the extra "response" wrapper that rocket_pants is adding.

What do you think will be the best way of using backbone with rocket_pants.
I was thinking about overriding some of rocket_pants methods to remove this or forking the project and get rid of the wrapper in general.

Cannot run rails server

$ rails serve
/Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/rocket_pants-1.5.4/lib/rocket_pants.rb:7:in require': cannot load such file -- moneta/memory (LoadError) from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/rocket_pants-1.5.4/lib/rocket_pants.rb:7:in<top (required)>'
from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/bundler-1.2.3/lib/bundler/runtime.rb:68:in require' from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/bundler-1.2.3/lib/bundler/runtime.rb:68:inblock (2 levels) in require'
from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/bundler-1.2.3/lib/bundler/runtime.rb:66:in each' from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/bundler-1.2.3/lib/bundler/runtime.rb:66:inblock in require'
from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/bundler-1.2.3/lib/bundler/runtime.rb:55:in each' from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/bundler-1.2.3/lib/bundler/runtime.rb:55:inrequire'
from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/bundler-1.2.3/lib/bundler.rb:128:in require' from /Users/witgo/work/code/tuan800_service/config/application.rb:14:in<top (required)>'
from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/railties-3.2.9/lib/rails/commands.rb:39:in require' from /Users/witgo/.rvm/gems/ruby-1.9.3-p327@rocketpants/gems/railties-3.2.9/lib/rails/commands.rb:39:in<top (required)>'
from script/rails:6:in require' from script/rails:6:in

'

$ gem list

*** LOCAL GEMS ***

actionmailer (3.2.9)
actionpack (3.2.9)
activemodel (3.2.9)
activerecord (3.2.9)
activeresource (3.2.9)
activesupport (3.2.9)
addressable (2.3.2)
api_smith (1.2.0)
archive-tar-minitar (0.5.2)
arel (3.0.2)
builder (3.1.4, 3.0.4)
bundler (1.2.3, 1.2.1)
capybara (2.0.1)
celluloid (0.12.4)
childprocess (0.3.6)
chinese_pinyin (0.4.1)
chronic (0.9.0, 0.8.0)
columnize (0.3.6)
connection_pool (1.0.0, 0.9.3, 0.9.2)
daemons (1.1.9)
debugger (1.2.2)
debugger-linecache (1.1.2)
debugger-ruby_core_source (1.1.5)
diff-lcs (1.1.3)
em-synchrony (1.0.2)
erubis (2.7.0)
eventmachine (1.0.0)
facter (1.6.16)
factory_girl (4.1.0)
factory_girl_rails (4.1.0)
fast_trie (0.5.0)
ffi (1.2.0)
fuzzy-string-match (0.9.4)
gsl (1.14.7)
hashie (1.2.0)
hike (1.2.1)
hiredis (0.4.5)
httparty (0.9.0)
i18n (0.6.1)
journey (1.0.4)
json (1.7.5)
levenshtein (0.2.2)
libwebsocket (0.1.7.1)
mail (2.5.3, 2.4.4)
mime-types (1.19)
moneta (0.7.1, 0.6.0)
mongoid (3.0.15, 3.0.14)
mongoid-rspec (1.5.5)
moped (1.3.2, 1.3.1)
multi_json (1.5.0)
multi_xml (0.5.1)
mysql2 (0.3.11)
narray (0.6.0.2)
net-http-persistent (2.8)
nilsimsa (1.1.2)
nokogiri (1.5.6, 1.5.5)
open4 (1.3.0)
origin (1.0.11)
perftools.rb (2.0.0)
polyglot (0.3.3)
rack (1.4.1)
rack-cache (1.2)
rack-mini-profiler (0.1.23)
rack-perftools_profiler (0.6.0)
rack-protection (1.3.2)
rack-ssl (1.3.2)
rack-test (0.6.2)
rails (3.2.9)
rails_config (0.3.2, 0.3.1)
railties (3.2.9)
rake (10.0.3, 10.0.0)
rdoc (3.12)
redis (3.0.2)
redis-namespace (1.2.1)
redis-objects (0.6.1)
resque (1.23.0)
rmmseg-cpp (0.2.9)
rocket_pants (1.5.4)
rsolr (1.0.8)
rspec (2.12.0)
rspec-core (2.12.2, 2.12.1)
rspec-expectations (2.12.1, 2.12.0)
rspec-mocks (2.12.1, 2.12.0)
rspec-rails (2.12.0)
ruby_core_source (0.1.5)
rubygems-bundler (1.1.0)
RubyInline (3.12.0, 3.11.4)
rubyzip (0.9.9)
rvm (1.11.3.5)
selenium-webdriver (2.27.2)
sidekiq (2.6.0, 2.5.4)
simhash (0.2.5)
sinatra (1.3.3)
slim (1.3.5, 1.3.4)
sprockets (2.8.2, 2.2.2)
temple (0.5.5)
thin (1.5.0)
thor (0.16.0)
tilt (1.3.3)
timers (1.0.2)
treetop (1.4.12)
tzinfo (0.3.35)
unicode (0.4.3)
vegas (0.1.11)
websocket (1.0.6, 1.0.4)
whenever (0.8.1, 0.8.0)
will_paginate (3.0.3)
xpath (1.0.0)
ZenTest (4.8.3)

ApiController naming if controller already exists?

I think I'm missing something super obvious, but what would be the directory structure if you had API controllers alongside existing 'regular' controllers?

From the README -

In your other controllers, such as users_controller.rb:
class UsersController < ApiController

So if I already have an /app/controllers/users_controller.rb defined, is there a standard place/name I should use for the new API controller?

Documentation on Post and Put methods

Hi, love rocket_pants as I am learning APIs. I think a big win for us nubes would be to include Post and Put requests (Create and Update methods) in the docs. Right now its just GET requests and index/show methods.

These examples are lacking here and in the linked sample app.

Thanks!

403 forbidden

Hey peeps,

I would be nice to have a 403 added to the list of out of the box errors.

ie error! :forbidden

Forced to require 'will_paginate' in environment.rb

If I don't require 'will_paginate' in my environment.rb file I get the following error:

undefined method `paginate' for #<ActiveRecord::Relation:0x007fd832b6e5b0>

Wanted to point this out and perhaps find some explanation for this.

Perhaps this is due to my application setup? Perhaps you will see if the issue stems from my Gemfile.lock (notice will_paginate is listed twice)? Let me know if you observe anything:

$ ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin12.2.0]
$ rails -v
Rails 3.2.11
$ bundle -v
Bundler version 1.2.3

This is the use case between the model and controller for the my resource

class Product < ActiveRecord::Base
  include RocketPants::Cacheable
  ...
end

class Api::ProductsController < RocketPants::Base
  version 1
  ...

def search
    ...
    expose Product.where("vendor_cats like ?", q).paginate(:page => params[:page])
end

And here is the relevant part of my Gemfile.lock

    rocket_pants (1.7.0)
      actionpack (>= 3.0, < 5.0)
      api_smith
      hashie (~> 1.0)
      moneta
      railties (>= 3.0, < 5.0)
      will_paginate (~> 3.0)
    sass (3.2.5)
    sass-rails (3.2.6)
      railties (~> 3.2.0)
      sass (>= 3.1.10)
      tilt (~> 1.3)
    seedbank (0.2.0)
    simple_form (2.0.4)
      actionpack (~> 3.0)
      activemodel (~> 3.0)
    simple_oauth (0.1.9)
    sprockets (2.2.2)
      hike (~> 1.2)
      multi_json (~> 1.0)
      rack (~> 1.0)
      tilt (~> 1.1, != 1.3.0)
    thor (0.17.0)
    tilt (1.3.3)
    treetop (1.4.12)
      polyglot
      polyglot (>= 0.3.1)
    tzinfo (0.3.35)
    uglifier (1.3.0)
      execjs (>= 0.3.0)
      multi_json (~> 1.0, >= 1.0.2)
    warden (1.2.1)
      rack (>= 1.0)
    weary (1.1.2)
      addressable (~> 2.3.2)
      multi_json (~> 1.3.0)
      promise (~> 0.3.0)
      rack (~> 1.4.0)
      simple_oauth (~> 0.1.5)
    will_paginate (3.0.4)

PLATFORMS
  ruby

DEPENDENCIES
  bootstrap-sass (~> 2.2.2.0)
  coffee-rails (~> 3.2.1)
  devise
  gilt
  high_voltage
  httparty
  ice_cube
  jquery-rails
  localtunnel
  multi_json (~> 1.3.0)
  omniauth-singly
  omniauth-twitter
  pg
  rails (= 3.2.11)
  rocket_pants
  sass-rails (~> 3.2.3)
  seedbank
  simple_form
  uglifier (>= 1.0.3)

Testing response codes while using Devise

Hi,

I've been getting into RocketPants for a project recently and all is going well. Thanks very much for taking the time.

I've run into an issue that I don't know how to solve and was after some guidance.

I'm getting the following error from my specs when I include the Devise Helpers. I should say that the service actually works when I access 'in the real world' and this only seems to be an issue with testing. I'd still like to solve it though.

Failures:

  1) Api::ThingsController should work
     Failure/Error: get :index, version: 1
     NoMethodError:
       undefined method `render' for #<Api::ThingsController:0x007fe1d310edb8>
     # ./spec/controllers/api/things_controller_spec.rb:15:in `block (2 levels) in <module:Api>'


rspec ./spec/controllers/api/things_controller_spec.rb:13 # Api::ThingsController should work

Line 15 in the spec is:

get :index, version: 1

It seems to be specific to RocketPants as I've got many other services defined inheriting from ApplicationController with devise authentication and I can check the response ok. I can also validate a 200 with a successful authentication on the ThingsController. I also get the same issue when using the 'authenticate_request' example that uses the warden request.

Here's the controller:

module Api
  class ThingsController < RocketPants::Base

    include Devise::Controllers::Helpers

    prepend_before_filter :get_auth_token
    before_filter :authenticate_user! # Doesn't work as Devise helpers don't work

    version 1

    def index
      expose Thing.paginate(:page => request.headers['X-Api-Page'])
    end

    private

    def get_auth_token
      if auth_token = params[:auth_token].blank? && request.headers['X-Auth-Token']
        params[:auth_token] = auth_token
      end
    end

  end
end

Here's the spec:

module Api
  describe ThingsController do
    it 'should work' do
      FactoryGirl.create(:thing)
      get :index, version: 1
      response.status.should == 401
    end
  end
end

Any help would be greatly appreciated.

Mongoid

Hello everyone I managed to make the error system work with mongoid using

ApiController < RocketPants::Base
  map_error! Mongoid::Errors::Validations do |exception|
    RocketPants::InvalidResource.new exception.record.errors
  end
end

Is it possible to add this lines to the documentations?

Authorization?

Sorry to do this as an issue, but I found no way to message you; no email on the GH account.

What's the recommended approach to take with RocketPants as far as providing authorization for specific API calls with something like CanCan or Declarative Authorization? Should that be done on a controller by controller basis? How do you guys handle it?

Kaminari instead of will_paginate

Hi, we're already using Kaminari in our rails app, is there an option to use it instead of having will_paginate in dependency in the gemspec? I see there's already some code/spec with kaminari, I don't know if it's 100% functional though!

Thanks

undefined method `_prefixes`

When I have a test for my controller that is this simple:

  it "gets a single product" do
    get :show, :id => product.to_param, :version => 1
  end

And the controller has no show action, upon running this test I am met with an ugly stacktrace:

1) Spree::Api::V1::ProductsController gets a single product
     Failure/Error: get :show, :id => product.to_param, :version => 1
     NameError:
       undefined local variable or method `_prefixes' for #<Spree::Api::V1::ProductsController:0x007fa802167680>
     # /Users/ryan/.rvm/gems/ruby-1.9.3-p0-falcon/gems/actionpack-3.2.2/lib/action_controller/metal/implicit_render.rb:14:in `method_for_action'
     # /Users/ryan/.rvm/gems/ruby-1.9.3-p0-falcon/gems/actionpack-3.2.2/lib/abstract_controller/base.rb:115:in `process'
     # /Users/ryan/.rvm/gems/ruby-1.9.3-p0-falcon/gems/actionpack-3.2.2/lib/action_controller/metal/testing.rb:17:in `process_with_new_base_test'
     # /Users/ryan/.rvm/gems/ruby-1.9.3-p0-falcon/gems/actionpack-3.2.2/lib/action_controller/test_case.rb:464:in `process'
     # /Users/ryan/.rvm/gems/ruby-1.9.3-p0-falcon/gems/actionpack-3.2.2/lib/action_controller/test_case.rb:49:in `process'
     # /Users/ryan/.rvm/gems/ruby-1.9.3-p0-falcon/gems/rocket_pants-1.0.0/lib/rocket_pants/test_helper.rb:77:in `process'
     # /Users/ryan/.rvm/gems/ruby-1.9.3-p0-falcon/gems/actionpack-3.2.2/lib/action_controller/test_case.rb:380:in `get'
     # /Users/ryan/Sites/gems/spree/api/spec/controllers/spree/api/v1/products_controller_spec.rb:13:in `block (2 levels) in <top (required)>'

I think that this should just tell you that the action couldn't be found in the controller, like normal.

Exposing deep resources

Sorry to be posting a question here , but did not know where else.
Is it possible to expose a nested resource. Let say User has many Addresses. So I wanna do this:

paginated User.includes(:addresses).all

clean way to check required fields for api calls?

Often, I have cases where the required field for an api call is not included, and something like params[:x][:y] would result in a 500 error if '?x[y]=12121' is not part of the call, showing my whole stack trace. I understand that I can write a bunch of boilerplate code to check every single case for all required fields missing for a call, but is there any clean way to check for required fields using rocketpants?

Thanks Darcy!
Jeff

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.