• Stars
    star
    103
  • Rank 333,046 (Top 7 %)
  • Language
    Ruby
  • License
    Other
  • Created over 12 years ago
  • Updated over 11 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

RubyMotion wrapper for NanoStore, a lightweight schema-less key-value document database based on sqlite.

NanoStore for RubyMotion

Wrapper for NanoStore, a lightweight schema-less key-value document database based on sqlite, in RubyMotion.

Status: Work in progress. API subject to change.

Find a sample application using NanoStore here

How to use Blog here

Installation

Install the CocoaPods dependency manager if you haven't it already:

gem install motion-cocoapods
pod setup

Install nano-store gem

gem install nano-store

Require nano-store to your project 'Rakefile'

$:.unshift("/Library/RubyMotion/lib")
require 'motion/project'
require 'rubygems'
require 'motion-cocoapods'
require 'nano-store'

Motion::Project::App.setup do |app|
  app.name = 'myapp'
  
  # Add the pod NanoStore to your project
  app.pods do
    pod 'NanoStore', '~> 2.6.0'
  end
end

Now, you can use NanoStore in your app.

Upgrade Notes

If you are upgrading from an older version of nano-store gem, make sure you run rake clean and remove vendor/Pods/build* folders before building your project. Otherwise you may still using the old binaries!

Basic Usage

Set default storage type

# memory only db
NanoStore.shared_store = NanoStore.store(:memory)

# file based db
documents_path         = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0]
NanoStore.shared_store = NanoStore.store(:file, documents_path + "/nano.db")

Define Model

class User < NanoStore::Model
  attribute :name
  attribute :age
  attribute :created_at
end

A key (UUID) that identifies the object will be added automatically.

Attributes must be serializable, which means that only the following data types are allowed:

  • NSArray
  • NSDictionary
  • NSString
  • NSData (*)
  • NSDate
  • NSNumber
  • NSNull
  • NSURL

Note

(*) The data type NSData is allowed, but it will be excluded from the indexing process.

Create

# Initialize a new object and save it
user = User.new(:name => "Bob", :age => 16, :created_at => Time.now)
user.save
user.key # => "550e8400-e29b-41d4-a716-446655440000" (automatically generated UUID)

# Create a new object directly
user = User.create(:name => "Bob", :age => 16, :created_at => Time.now)

Retrieve

# find all models
User.all # => [<User#1>, <User#2>]

# find model by criteria
users = User.find(:name, NSFEqualTo, "Bob")

# or use Hash
users = User.find(:name => "Bob")
users = User.find(:name => { NSFEqualTo => "Ronald" })
users = User.find(:name => { NSFEqualTo => "Ronald" }, :age => { NSFGreaterThan => 50 })

# or use Array for matching multiple values
users = User.find(:name => ["Bob", "Ronald", "Ken"])

# Optionally sort the result with additional hash parameters
users = User.find({:age => { NSFGreaterThan => 10 }}, {:sort => {:age => :desc}})

Update

user = User.find(:name, NSFEqualTo, "Bob").first
user.name = "Dom"
user.save

Delete

user = User.find(:name, NSFEqualTo, "Bob").first
user.delete

# Bulk delete
User.delete(:age => {NSFGreaterThan => 20})

Using Transaction

Use transaction is easy, just wrap your database code in a transaction block.

store = NanoStore.shared_store = NanoStore.store

begin
  store.transaction do |the_store|
    Animal.count # => 0
    obj1 = Animal.new
    obj1.name = "Cat"
    obj1.save
      
    obj2 = Animal.new
    obj2.name = "Dog"
    obj2.save
    Animal.count # => 2
    raise "error"  # => an error happened!
  end
rescue
  # error handling
end

Animal.count # => 0

Using Bags

A bag is a loose collection of objects stored in a document store.

store = NanoStore.store
bag = Bag.bag
store << bag

# add subclass of NanoStore::Model object to bag
page = Page.new
page.text = "Hello"
page.index = 1
bag << page 
    
# save the bag
bag.save
  
# obtain the bags from document store
bags = store.bags

Association

Use bag to declare a Bag that associated with a Model.

class User < NanoStore::Model
  attribute :name
  attribute :age
  attribute :created_at
  bag :cars
end

class Car < NanoStore::Model
  attribute :name
  attribute :age
end

user = User.new(:name => "Peter", :age => 20, :created_at => Time.now)
user.cars << Car.new(:name => "Mini", :age => 0)
user.save

user.cars # => #<NanoStore::Bag:0x7411410> 

KVO

If you are using NanoStoreInMotion with KVO, aware that NanoStore::Model actually store data in a field info and create methods dynamically. Instead of listening on the field name field_name, you should listen on key path info.field_name.

For example, instead of following code:

class Radio < NanoStore::Model
  attribute :name
end

radio = Radio.new
radio.addObserver(observer, forKeyPath:"name", options: NSKeyValueObservingOptionNew, context: nil)

You should do:

radio = Radio.new
radio.addObserver(observer, forKeyPath:"info.name", options: NSKeyValueObservingOptionNew, context: nil)

Performance Tips

NanoStore by defaults saves every object to disk one by one. To speed up inserts and edited objects, increase NSFNanoStore's saveInterval property.

Example

# Create a store
store = NanoStore.shared_store = NanoStore.store
    
# Increase the save interval
store.save_interval = 1000

# Do a bunch of inserts and/or edits
obj1 = Animal.new
obj1.name = "Cat"
store << obj1

obj2 = Animal.new
obj2.name = "Dog"
store << obj2

# Don't forget that some objects could be lingering in memory. Force a save.
store.save

Note: If you set the saveInterval value to anything other one, keep in mind that some objects may still be left unsaved after being added or modified. To make sure they're saved properly, call:

store.save

Choosing a good saveInterval value is more art than science. While testing NanoStore using a medium-sized dictionary (iTunes MP3 dictionary) setting saveInterval to 1000 resulted in the best performance. You may want to test with different numbers and fine-tune it for your data set.

Credit

  • Based on NanoStore from Tito Ciuro, Webbo, L.L.C.

License

BSD License

More Repositories

1

IGHTMLQuery

IGHTMLQuery is a lightweight XML/HTML parser for Objective-C, built on top of libxml.
Objective-C
282
star
2

react-native-htmltext

Use HTML like markup to create stylized text in ReactNative.
JavaScript
141
star
3

QuickJS-iOS

Build QuickJS Library for iOS
Makefile
100
star
4

IGFastImage

Finds the size and type of an image given its uri by fetching as little as needed.
Objective-C
95
star
5

peerflix-ios

Streaming torrent client for iOS
Swift
85
star
6

websnap

Create snapshot of webpage
HTML
70
star
7

zhconv

利用 MediaWiki 作中文繁簡互換,支援地區詞處理 (大陸、香港、台灣及新加坡)
Ruby
60
star
8

IGAutoCompletionToolbar

IGAutoCompletionToolbar is a UICollectionView subclass created to display auto completion via a keyboard accessory view.
Objective-C
60
star
9

instant

An experiment on real time visualize development tool, inspired by Bret Victor's Inventing on Principle talk and @ermau C# Implementation.
JavaScript
49
star
10

IGJavaScriptConsole

A JavaScript/Ruby REPL for your Objective-C apps.
Objective-C
48
star
11

UniversalDetector

Wrapper of uchardet for Objective-C. UniversalDetector takes a sequence of bytes in an unknown character encoding without any additional information, and attempts to determine the encoding of the text.
HTML
44
star
12

IGDigest

Provides convenient wrappers for popular message digest formats (MD5, SHA1 and SHA256) and HMAC (Hash-based message authentication code).
Objective-C
41
star
13

hpple-motion

deprecated.
Ruby
39
star
14

IGSearch

A simple Objective-C full text search engine with CJK support.
Objective-C
35
star
15

JavaScriptCoreOpalAdditions

Ruby for native Objective-C apps!
Ruby
33
star
16

libupskirt

Please do not use this fork, use the origin repo at http://fossil.instinctive.eu/libupskirt/home
C
31
star
17

motion-logger

A thin wrapper of CocoaLumberjack for RubyMotion.
Ruby
30
star
18

IGWebLogger

IGWebLogger allows you to view your iOS app logs over web browser in realtime.
Objective-C
30
star
19

guard-xctool-test

Automatically run test on changed files when developing on XCode.
Ruby
29
star
20

NSData-MD5

Add MD5 to NSData
Objective-C
27
star
21

motion-schemes

Expand RubyMotion build system to support building multiple apps from one project.
Ruby
25
star
22

CSSSelectorConverter

A CSS Selector to XPath Selector converter for Objective-C.
Objective-C
24
star
23

IGScraperKit

Create dynamic web scraper in Objective-C or Ruby!
HTML
23
star
24

itunes-auto-ingestion

A simple port of Apple itunes Autoingestion tool to ruby.
Ruby
22
star
25

Motion-Cocos2d-Blocks

A simple puzzle game built using RubyMotion and cocos2D for iPhone.
Ruby
20
star
26

YapModel

YapModel is a DSL for working with YapDatabase.
Objective-C
19
star
27

wakizashi

HTML/XML parser for RubyMotion, based on GDataXML-HTML
Ruby
19
star
28

CTidy

libtidy Objective-C wrapper
C
19
star
29

EvalJS

EvalJS lets you run JavaScript code from your iOS app.
C
18
star
30

moria

Auto Layout in RubyMotion.
Ruby
18
star
31

CuratorScreenSaver

小海嚴選正妹 Screen Saver for Mac
Objective-C
16
star
32

PlayHKTV

Unofficial Mac app to watch HKTV
Objective-C
15
star
33

RubyMotion-PocketCoreImage

A reimplementation of PocketCoreImage sample from Apple using RubyMotion
Ruby
14
star
34

proxy_list

Gather list of proxies from various sources, validate them and rotate them for use.
Ruby
13
star
35

Deliver.app

An app to upload screenshots and metadata to App Store. Frontend for deliver.
Swift
13
star
36

react-split-layout

A React component that separate two or more views with a draggable divider.
JavaScript
11
star
37

express-pouchdb-jwt

Authenticate PouchDB using JSON Web Token
JavaScript
10
star
38

cantonese-syllables

Scrape cantonese syllables from CUHK Multi-function Chinese Character Database.
Ruby
10
star
39

iloveck101

我愛卡提諾 for iOS
Objective-C
10
star
40

SparrowInMotion

Demo to use Sparrow Framework - The Open Source Game Engine for iOS - in RubyMotion.
Ruby
10
star
41

xmlwise

a fork of xmlwise at http://code.google.com/p/xmlwise/
Java
9
star
42

motion-objc

(deprecated) Simply add objective-C files to your RubyMotion project
Ruby
9
star
43

NanoStoreModel

Quick and easy way to use NanoStore as your model.
Objective-C
9
star
44

IGFuture

Simple futures pattern in Objective-C.
Objective-C
9
star
45

legco-hansard-parser

A script to convert and parse legco meeting hansard into machine readable data.
Ruby
8
star
46

todomvc-meteor

A todo app in Meteor.js, inspired by todomvc
CoffeeScript
8
star
47

pouchdb-replication-folder

Replicate PouchDB/CouchDB database with a shared folder (e.g. Dropbox, iCloud Drive ...etc)
JavaScript
8
star
48

BSMInputMethod

筆順碼輸入法 - BSM Input Method for Mac OS X (10.8+)
Objective-C
7
star
49

cardjour

Share business card (VCard) with others in LAN, using Bonjour
Ruby
7
star
50

motion-dtrace

Proof of concept to use dtrace on rubymotion
D
7
star
51

torrent-finder

Extensible command line tool to search torrent.
Ruby
7
star
52

jsonsql

Execute SQL against set of JSON files.
Ruby
7
star
53

ViewQuery

ViewQuery is a lightweight jQuery style view selector library for UIKit, based on Igor selector engine.
Objective-C
7
star
54

IGSignature

Objective-C client of signature gem. Sign API call with shared secret and timestamp using SHA256 HMAC.
Objective-C
7
star
55

charlock_holmes-jruby

Character encoding detecting library for JRuby using ICU4J.
Racket
7
star
56

appfigures

Ruby
7
star
57

localhook

Localhook let you receive webhooks behind a firewall.
Ruby
7
star
58

motion-simple-profiler

A RubyMotion extension to log method runtime without adding a single line of code to original class.
Ruby
7
star
59

motion-static-sample

Sample to use RubyMotion static library in a Objective-C project
Objective-C
7
star
60

jquery.tableparser

jQuery plugin to parse HTML table into Arrays
JavaScript
7
star
61

SwiftyDispatch

A lightweight GCD wrapper for Swift.
Swift
6
star
62

IGAutoString

Convert string in arbitary encoding to NSString in Objective-C.
Objective-C
6
star
63

motion-dryer

DRY your RubyMotion project
Ruby
6
star
64

rb-moretext

Use MoreText.js to generate chinese text for good.
Ruby
6
star
65

markdown-slides

Create HTML based presentation using markdown!
JavaScript
6
star
66

quiz1

Java Quiz #1 - Find the best value McDonald Order!
Java
5
star
67

mtrupdate_analyze

Aggregate @mtrupdate tweets
Ruby
5
star
68

tappy

Twitter API Proxy in Ruby -- filter annoying twitter client such as Foursquare
Ruby
5
star
69

table_parser

Parse complex HTML table with ease
Ruby
5
star
70

embed_html

Download and embed images in html using base64 data encoding
Ruby
5
star
71

hk-node-js

homepage for Hong Kong Node of Javascripters
CoffeeScript
5
star
72

codename

Codename gem randomly generate codename based on list of sources.
Ruby
5
star
73

Backbone.memorySync

Simplistic memory-only sync adapter for Backbone. It's a drop-in replacement for Backbone.Sync() to handle saving to memory. Use for testing or volatile data that need no persistence.
JavaScript
5
star
74

node-hearthstone

Utilities for Hearthstone
JavaScript
5
star
75

RubyMotionCocos2d-Static

experment to use cocos2d in rubymotion, with static library
Ruby
5
star
76

Alt

Another Flux implementation for Swift.
Swift
5
star
77

MasonryGenerator

A Mansory extension to generate native NSLayoutConstraint code from Mansory code.
Objective-C
5
star
78

TwitLongerAPI

TwitLongerAPI is a TwitLonger API implemented with Objective-C programming language.
Objective-C
4
star
79

llama.swift

This package provides Swift bindings for llama.cpp
Swift
4
star
80

RubyQuery

jQuery for command line and ruby. It make extract simple data fun and easy.
Ruby
4
star
81

rubberband-audio

Ruby interface for Rubber Band Library.
Ruby
4
star
82

hk_geo

geolocation transormation api for hk
Ruby
4
star
83

jswarrior

JavaScript
4
star
84

ASIHTTPRequestStatic

a static library of ASIHTTPRequest
4
star
85

woot-doc

A WOOT(“WithOut Operational Transformation”) data structure for p2p collaborative apps
JavaScript
4
star
86

pdbook

Convert PDB (Palm Database) Ebook to PDF format. Specially handle document from haodoo.net.
Ruby
4
star
87

hearthstone

Utilities for Hearthstone
JavaScript
4
star
88

UserSettingsModel

Experimental RubyMotion module to allow using user settings as data model
Ruby
4
star
89

ffmpeg-tvos-precompiled

ffmpeg-tvos-precompiled
C
3
star
90

IGXMLReader

A XML Pull Parser based on libxml for Objective-C
Objective-C
3
star
91

Share-More-for-Android

Add subject to URL, when using "Share" option in android apps
Java
3
star
92

datamining

Notes on reading OReilly's "Progamming Collective Intelligence"
Ruby
3
star
93

guard-sprockets-boilerplate

a web project boilerplate use guard and sprockets to watch and compile your static assets
Ruby
3
star
94

vagrant-osx-elcapitan-build

Vagrant image to build iOS applications
3
star
95

uoav-client

Unofficial AirVideo Client
Java
3
star
96

docker-backup

Use Backup gem to backup docker volume
Ruby
2
star
97

PonyDebugger-CocoaLumberjack-bridge

Bridge PonyDebugger and CocoaLumberjack.
Objective-C
2
star
98

rpi-postgres

Postgres docker image for RaspberryPi
Shell
2
star
99

localhook-server

Localhook let you receive webhooks behind a firewall.
Ruby
2
star
100

rpi-phantomjs

PhantomJS image for Raspberry Pi
2
star