Code Monkey home page Code Monkey logo

cappuccinoresource's Introduction

CappuccinoResource

Cappuccino on Rails. CappuccinoResource (CR) is like ActiveResource for your Cappuccino project!

Installation

Install with ease using the Narwhal package manager

tusk update && tusk install CappuccinoResource

Once that completes, you can simply @import it into your project

@import <CappuccinoResource/CRBase.j>

Optionally, install manually by copying /Framework/CappuccinoResource/*.j into your project and @import CRBase.j where needed

    @import "CRBase.j"

Usage

There is now an open-source demo application demonstrating basic usage. The demo is available on Heroku, and the source is available on GitHub. For more detailed instructions, read on.

In Rails

Make sure your RESTful controllers render json. You can take or leave the respond_to block depending on your needs.

Rails 2 Example:

class PostsController < ApplicationController

  def index
    @posts = Post.all

    respond_to do |format|
      format.html
      format.json { render :json => @posts }
    end
  end

  # other actions ...
end

Rails 3 Example:

class PostsController < ApplicationController
  respond_to :html, :json

  def index
    @posts = Post.all
    respond_with(@posts)
  end

  # other actions ...
end

In Capp

Create a class which inherits from CR:

@implementation Post : CappuccinoResource
{
    CPString title        @accessors;
    CPString body         @accessors;
    CPDate   publishedOn;
    BOOL     isViewable;
}

- (JSObject)attributes
{
    return {
      "post": {
        "title":title,
        "body":body,
        "published_on":[publishedOn toDateString],
        "is_viewable":isViewable
      }
    };
}

The attributes instance method MUST be declared in your class for it to save properly.

CR performs naïve class pluralization (it just adds an "s"). If your class name has a more complex inflection, you can simply override the resourcePath class method. For instance, a Person class:

@implementation Person : CappuccinoResource
{
    CPString name;
}

+ (CPURL)resourcePath
{
    return [CPURL URLWithString:@"/people"];
}

- (JSObject)attributes
{
    return {"person":{"name":name}};
}

@end

Using your new class should feel familiar to Rails devs.

CRUD

Instantiate a blank Post object

var post = [Post new];

Optionally declare attributes at the same time. JSON feels like Ruby hashes!

var post = [Post new:{"title":"First Post!","body":"Lorem and stuff"}];

Just like in ActiveResource, create = new + save

var post = [Post create:{"title":"First Post!","body":"Lorem and stuff"}];

Get all the posts from Rails

var posts = [Post all];
[posts class]; // CPArray
[[posts objectAtIndex:0] class]; // Post

You can fetch a resource with its identifier...

var post = [Post find:@"4"];

Change its title...

[post setTitle:@"Shiny New Name"];

And save it in your Rails back-end.

[post save];

Deleting is just as easy

[post destroy];

More Advanced Finds

You can also run find with JSON paramaters (or a CPDictionary)

var myPost = [Post findWithParams:{"title":"Oh Noes!"}];
[myPost class]; // Post

Or the same thing with a collection

var posts = [Post allWithParams:{"body":"happy"}];
[posts class]; // CPArray
[[posts objectAtIndex:0] class]; // Post

The parameters will get serialized and be available to your Rails controller's params hash. It's up to Rails to return the appropriate records.

Custom Identifiers

You don't need to use the default Rails id in your URLS. For example, if you'd rather use the login attribute as a unique identifier, overwrite your class's identifierKey class method like this:

+ (CPString)identifierKey
{
    return @"login";
}

CR will take care of the rest.

Notifications

There are multiple events you can observe in the life cycle of a CR object. The notification names are comprised of the object's class name followed by the event name. So, for a Movie class which inherits from CR, the list of observable events are:

  • MovieResourceWillLoad
  • MovieResourceDidLoad
  • MovieCollectionWillLoad
  • MovieCollectionDidLoad
  • MovieResourceWillSave
  • MovieResourceWillCreate
  • MovieResourceWillUpdate
  • MovieResourceDidSave
  • MovieResourceDidCreate
  • MovieResourceDidUpdate
  • MovieResourceDidNotSave
  • MovieResourceDidNotCreate
  • MovieResourceDidNotUpdate
  • MovieResourceWillDestroy
  • MovieResourceDidDestroy

One thing worth pointing out; whenever you try to save a resource, it will post 2 notifications per event. The first is the Will/Did/DidNot Save notification. The second is either Will/Did/DidNot Create or Will/Did/DidNot Update depending on what type of a save it is.

Contributing

Please do! Like so:

  1. Fork CR
  2. Pass all tests (see below)
  3. Create a topic branch - git checkout -b my_branch
  4. Push to your branch - git push origin my_branch
  5. Pass all tests
  6. Create an Issue with a link to your branch

Testing

Please include passing tests with any proposed additions/modifications. To run the test suite:

  1. Install ojmoq: sudo tusk install ojmoq
  2. Run tests with: jake test OR ojtest Tests/*Test.j OR autotest

Credit

Much of this library was inspired by other open-source projects, the most noteworthy of which are:

  1. CPActiveRecord
  2. ObjectiveResource

I'd like to thank their authors for opening their source code to others.

Todo List

  • Infer -attributes from ivars (maybe with @property?)
  • Better error handling
  • Validations
  • Callbacks
  • Nested Models

Meta

Author

Jerod Santo

Contributors

Just me so far!

License

MIT Stylee

cappuccinoresource's People

Contributors

43n79w avatar benlangfeld avatar binaryways avatar jerodsanto avatar pepijn 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

cappuccinoresource's Issues

Nested Model Hack

So here's what I did to get nested models to work. I needed to to this to reduce the amount of http requests and database requests.

  1. In rails, included associations by overriding the to_json method in the model class. This is the only way I know to have rails include the root class for the associations.

class Post < ActiveRecord::Base
def to_json(args)
super( :methods => [:comments])
end

  1. Added a case to the switch function in setAttributes: method in CappuccinoResource class in CRBase.j
    case "object":
    [self setValue:[CPString JSONFromObject:value] forKey:attributeName];
    break;

  2. Added a method to CappuccinoResource class to be overridden in all subclasses that have associations

  • (void)convertAssociations
    {
    //Overide in Model classes
    }
  1. added a method call to + (id)new:(JSObject)attributes right before the return statement:
    [resource convertAssociations];

  2. In parent object, for example Post.j added the declaration
    CPArray comments @accessors;

  3. and overrode -(void)convertAssociations method

  • (void)convertAssociations
    {
    [self setComments:[Comment collectionDidLoad:comments]];
    }
  1. The child class, in this case Comment.j, I set up just like a regular CappuccinoResource subclass.

  2. Now in my controllers I can access the associated models like any other attribute
    [post comments]

I've only tested reading from Rails, haven't saved to Rails yet.

Using another URL to fetch data

Hi,

I don't know if it's actually possible but it would be great to be able to specify the main domain/url from where we want to fetch data.

Incorrect handling of update responses

CappuccinoResource expects updated records to return the object in the body of the response, but respond_with only does this for create. resourceDidSave should only set attributes if there is a body present.

Patch to follow.

Support for json when ActiveRecord::Base.include_root_in_json is false

When ActiveRecord::Base.include_root_in_json is set to false, CappuccinoResource stops working.

The workaround is simple, all the "attributes = response[[self railsName]]" must be replace by "attributes = response".

Of course, a configuration option would be most welcome. I will see if I can create a patch.

findWithParams error

Before I explain the issue I just want to thank you!!! for this great library it really make my life a lot!! easier .. Thanks!!

I found a really simple issue when I call findWithParams and the server return nothing (weird case) this method does not ask if the array has elements or not it directly return the first element and because the array it is empty you get an error. Also this issue is related to the method collectionDidLoad where you actually receive the server response. I think you shold ask if aResponse is empty also.

I made little changes to CRBase.j in order to fix the issue do you want me to send it to you or with this information is enough?

Again Thanks!! Great library!!

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.