Coder Social home page Coder Social logo

maglev's Introduction

DEPRECATED - please use motion-resource

Maglev

Faster, smoother iOS development. Pushing RubyMotion as hard as we can.

It's a Rails pun.

Still baking.

Models

Connect your models to your backend insanely fast.

Imagine http://thiswebsite.com/users/1.json returns something like:

{
    "id": "123",
    "name": "Clay",
    "posts": [{
        "id": "321",
        "name": "My First Post",
        "body": "Maglev is super neat"
    }]
}

We can define our models like this:

class User < Maglev::Model
  remote_attributes :id, :name

  has_many :posts

  collection_path '/users'
  member_path '/users/:id'
end

class Post < Maglev::Model
  remote_attributes :id, :name, :body

  belongs_to :user
end

Hook up our API like this:

Maglev::API.setup do
  root 'http://thiswebsite.com'
end

And grab all of our objects with nifty methods:

User.find(1) do |user|
  p user.posts.first.body
  # => Maglev is super neat
end

What about /users.json? It returns a structure like this:

{
    "users": [{
        "id": "123",
        "name": "Clay",
        "posts": [...]
    }]
}

User.find_all do |users| works out of the box.

Nested Collections

It is possible to do nested collections like this:

class Event < Maglev::Model
  remote_attributes :id, :name

  has_many :photos,
    collection_path: "/events/:id/photos",
    member_path: "/events/:event_id/photos/:id"

  def event_id
    self.id
  end
end

class Photo < Maglev::Model
  remote_attributes :id, :event_id, :url
  belongs_to :event
end

event = Event.new(...)

event.photos.find_all do |photos|
end

event.photos.find(13) do |photo|
end

Handeling Irregular Structure

Most JSON APIs return keys that don't always correspond to resource names. Maglev handles these flawlessly with the json_path property on most resources:

class User < Maglev::Model
  remote_attribute :city, json_path: "address.city"

  has_many :posts, json_path: "data"

  collection_path '/users', json_path: "members"
end

Thus, our /users would return something like:

{
    "members": [{
        "id": "123",
        "name": "Clay",
        "address": {
            "city": "San Francisco",
            "state": "CA"
        }
        "data": [...]
    }]
}

Notice how User#city is a nested resource inside the JSON; you can dig through the JSON with the value-path syntax.

Support Classes

The Maglev::Support module contains many wrappers and shortcuts that you could find useful in your project.

Transformer

A wrapper for NSValueTransformer:

# Creates a non-reversable NSValueTransformer
string_to_color = Maglev::Support::Transformer.to(NSString) do |value|
  UIColor.send("#{value.downcase}Color")
end

# Creates a reversable NSValueTransformer
bidirectional = Maglev::Suport::Transformer.to(NSString) do |value, reversed_value|
  if reversed_value
    get_string_for_color(reversed_value)
  else
    UIColor.send("#{value.downcase}Color")
  end
end

Examples

Please check the examples

maglev's People

Contributors

clayallsopp avatar gillygize avatar muescha 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

maglev's Issues

Load JSON from file

I need to load the JSON from a file on the device, instead of from the internet. How would I go about this with Maglev?

My JSON look like this:

{
  id: "made"
  headline: "<img class='logo_image' src='http://res.cloudinary.com/uninkd/image/upload/v1370715824/m6frudhoycatz4rtufix.jpg'>"
  issues: [1]
  0:  {
    id: "re-make"
    headline: "<h6 class='issue_title'>ISSUE NO 1 &#183; MAY 23 2013</h6>"
    color: "#49ABFF"
    name: "ISSUE NO 1"
    date: "2013-05-23T19:19:15Z"
    articles: [2]
    0:  {
      id: "inside-makerminds"
      headline: "<h1 class='headline'>Inside makerminds</h1>"
      lead: "<p class='light_grey lead'>A quick peek into what’s on our maker minds. From clothing company to motion sensors and disruptors of the consumer banking industry.</p>"
      image: "<img class='article_image' src='Inside_Makerminds.jpg'>"
      body: "<p class='body'><p><a href="http://www.betabrand.com/">Betabrand</a>&nbsp;is a new clever online-only clothing company based in - of course - San Francisco. They design, manufacture and “releasn clothing with new items available every week. What makes them stand out aside from their very quirky Northern California take on Hipster clothes is that they offer customers to model their clothing for a discount and asks their community what they should make next.&nbsp;<br><br><a href="http://www.misfitwearables.com/">Misfit Wearables</a>&nbsp;asked for $100K and raised over $800K on the crowdfunding platform&nbsp;<a href="http://www.indiegogo.com/projects/misfit-shine-an-elegant-wireless-activity-tracker?website_name=misfitshine">Indiegogo</a>&nbsp;for their motion tracker Shine. But their rationale was never the money alone but the product feedback and consumer validation that the 8,000 funders could offer. The product builds on Fuelband and Fitbit’s shortcoming and offers a product that syncs via touch, works when biking and swimming and offers an open API. The price was also very favorable for the early funders, starting at $49 and now post-funding retails at $99. The first 5,000 Shines are slated for delivery June 1.<br><br><a href="https://www.gobank.com/">GoBank</a>&nbsp;is joining&nbsp;<a href="https://www.simple.com/">Simple</a>&nbsp;to disrupt the gridlocked and charger happy consumer banking industry. The both offer the most basic features: debit card, virtual checks, mobile deposits and easy-to-use mobile and web interfaces. While Simple is still exploring different revenues streams, GoBank has introduced “Pay What You Want” in yearly membership fees and custom designed debit cards. They both share their idea of no hidden fees.&nbsp;<br><br>The Internet of Things is often mentioned but rarely exemplified.&nbsp;<a href="http://ninjablocks.com/">Ninja Blocks</a>&nbsp;is making hardware that communicates via your local network. The current connected sensors offered are motion sensors, temperature and humidity sensor, window and door contact sensor and ring button. But Ninja block also works with the so called actuators that can remotely turn off and on different wired devices. By connecting the temperature sensor to your WiFi and adding a few rules you could get an email alert when the temperature drops under or exceeds a certain temperature.<br><br>It’s impossible to write about Makers without mentioning two must-reads: Cory Doctorow’s futuristic story&nbsp;<a href="http://www.amazon.com/Makers-ebook/dp/B003VTZU1Q/ref=tmm_kin_title_0?ie=UTF8&amp;qid=1366657085&amp;sr=8-1">Makers</a>&nbsp;and Chris Anderson’s here-and-now&nbsp;<a href="http://www.amazon.com/Makers-The-Industrial-Revolution-ebook/dp/B0083DJUMA/ref=sr_1_1?s=digital-text&amp;ie=UTF8&amp;qid=1366657155&amp;sr=1-1&amp;keywords=chris+anderson+makers">Makers - The New Industrial Revolution</a>. Both books describe - from very different perspectives - the tectonic shift that is happening within manufacturing.</p></p>"
      byline: "<hr><p class='light_grey byline'>BY <b>PER HåKANSSON</b></p>"
      name: "Inside makerminds"
      url: "http://made.uninkd.com/issue/re-make/article/inside-makerminds"
    }-
    1:  {
      id: "doing-one-thing-well-works"
      headline: "<h1 class='headline'>Doing one thing well works</h1>"
      lead: "<p class='light_grey lead'>In a world where Silicon Valley rules and brand extensions are perceived as the natural growth strategy, the mono product jeans maker Hiut Denim from Cardigan, Wales stands out as a fresh outlier. Branding is never going to be the same.</p>"
      image: "<img class='article_image' src='Doing_One_Thing_Well_Works.jpg'>"
      body: "<p class='body'><p>A small town in Wales made jeans for over three decades. As much as 10% of the population were involved in the manufacturing. One day the factory closed down and moved away. Left were the mastery of how to make fantastic jeans. The Hiut Denim Company was started to put those skills to work again and to breathe life into their beloved town.&nbsp;<br><br>Their story - which also happens to be true - resonates with people and their jeans have become very popular across the world among the early adopter crowd through earned media. But what makes them even more unique is that they are - in a world that is frantically multi-tasking and diversifying - committed to only doing one thing and doing it really well: jeans made to last. They only offer two types of denim in two different cuts for men - women have to wait until later this year. And every year they have a new release with upgrades based on their user’s feedback.<br><br>The jeans are sold primarily via their online shop but now also through select local retailers. Every pair of jeans have an unique number on the inside which can be registered with HistoryTag.com to capture it’s timelime to be shared with the world via Twitter. Hiut Denim creates the first tag with the name of the jeans master, the date of manufacturing and a few photos. The second tag is usually by the new owner, telling his followers that he has received his first Hiut jeans.<br><br>The jeans are designed to be simple and understated. If it wasn’t for their distinct logo - a red owl - on the rivet of the left back pocket the jeans would be unrecognizable for the untrained eye. But once you have owned one for a few weeks you start recognizing others wearing the very same jeans and that could be the start of a very beautiful friendship. It could be the selvedge, the high quality denim, the stitching or how they age beautifully into being yours. Hiut recommends not washing a new pair of jeans for at least 6 months so that your personal body fats in combination with everyday wear can allow for the jeans to hug you in the right places and create real wrinkles that could be yours.<br><br>Hiut Denim is not really a brand but the next generation lovemark. They have been brilliant at taking an iconic piece of clothing and making it matter again on a new level. Everything with their story resonates with people: make to last, honor craftsmanship, do things well, care about your community, care about people, think long-term, work hard and have fun.&nbsp;<br><br>Everything Hiut shares via their Twitter stream, weekly email newsletter and inspirational physical yearbook is turning into social objects that starts conversations. But it’s never about the transactional experience of the jeans but the transformational experience of having a purpose, a strong culture and making what matters. That’s what their brand “experience” is about. It’s not about them, it’s about you.<br><br>In a world where cheaper, faster and more short-term seems to be the prevalent modus operandi, Hiut is the honest, transparent and authentic challenger of the mindless business technorati culture. They are living their dream by using technology as an instrument, not a crutch and we are all invited to participate in their conquest of happiness without any false product promises or commitments to buying their jeans. That said, once you have tried on a pair of their jeans you never want to give them back no matter what. And that is genius.</p></p>"
      byline: "<hr><p class='light_grey byline'>BY <b>PER HåKANSSON</b></p>"
      name: "Doing one thing well works"
      url: "http://made.uninkd.com/issue/re-make/article/doing-one-thing-well-works"
    }
  }

I have 3 models:

class Publication < Maglev::Model
  remote_attributes :id, :headline

  has_many :issues

  collection_path ''
  member_path ''
end

class Issue < Maglev::Model
  remote_attributes :id, :headline, :color, :name, :date

  has_many :articles
  belongs_to :publication

  collection_path '/articles'
  member_path '/article/:id'
end

class Article < Maglev::Model
  remote_attributes :id, :headline, :lead, :image, :body, :byline, :name, :url

  belongs_to :issue
end

How would I go about loading my JSON from a file instead of an url and how would you go about linking it up to the models when my JSON file doesn't have a /publications extension?

Is this even possible with Maglev?

undefined method force_remote_relationship_syntax

https://github.com/steakknife/maglev-station-closed-temporarily

rm -rf vendor && bundle && rake

2013-05-23 13:43:30.872 ios[82448:11603] undefined method `force_remote_relationship_syntax' for Maglev:Class (NoMethodError)
2013-05-23 13:43:30.881 ios[82448:11603] *** Terminating app due to uncaught exception 'NoMethodError', reason: 'undefined method `force_remote_relationship_syntax' for Maglev:Class (NoMethodError)
'
*** First throw call stack:
(0x1b76012 0x6c5e7e 0x3136a4 0x3222 0x2675)
libc++abi.dylib: terminate called throwing an exception
                                                            rake aborted!
Command failed with status (1): [DYLD_FRAMEWORK_PATH="/Applications...]
/Library/RubyMotion/lib/motion/project/template/ios.rb:93:in `block in <top (required)>'
Tasks: TOP => default => simulator
(See full trace by running task with --trace)

git://github.com/clayallsopp/maglev.git (at master) is not checked out. Please run `bundle install`

I'm getting this error, even though I've run bundle install and everything. I'm not sure if it is my bundler that is out of order. If it is, then please close the issue.

Error:

git://github.com/clayallsopp/maglev.git (at master) is not checked out. Please run `bundle install`

Gemfile:

source "https://rubygems.org"

gem "teacup"
gem "sugarcube"
gem "sweettea"
gem 'bubble-wrap', :path => '~/Projects/*Defaults/Misc/Cocoapods/BubbleWrap', :branch => 'master'
# gem 'bubble-wrap', "~> 1.3.0"
gem "geomotion"
gem "motion-schemes"
gem "motion-cocoapods"
gem "afmotion"
gem "maglev", :git => "git://github.com/clayallsopp/maglev.git"
gem "json_read_write", :path => '~/Projects/*Defaults/Misc/Cocoapods/JSONReadWrite', :branch => 'master'
# gem "json_read_write", :git => "git://github.com/holgersindbaek/JSONReadWrite.git", :branch => "master"
# gem 'const_cache'

group :development do
  gem "awesome_print_motion"
end

uninitialized constant YAML (NameError)

Here is my Gemfile (builds with maglev commented out)

source 'https://rubygems.org'

gem "ProMotion", :git => '[email protected]:clearsightstudio/ProMotion.git'
gem 'motion-config-vars'
gem "maglev", :git => "git://github.com/clayallsopp/maglev.git"

more examples from remote_model

i like to see more examples here in maglev readme copied from the remote_model readme (if they still working with maglev)

Nested collection paths

Is it possible to do nested collection paths, let's say

class Event < Maglev::Model
  remote_attributes :id, :name
  has_many :photos
end

class Photo < Maglev::Model
  remote_attributes :id, :event_id, :url
  belongs_to :event

  collection_path "/events/:event_id/photos/:id"
end

question: example of how to set authentication

Hi,

How do you set authentication in Maglev::API.setup? I cant find an example and i've tried a few combinations without success.

In BW, it would be something like

BW::HTTP.get("http://mysite.com/resource", {credentials: {username: 'john', password: 'API'}}) do |response|
p response.body.to_str # prints the response's body
end

but I dont see how to pass these credentials into Maglev::API.setup.

Thanks.

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.