百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
M

MotionModel

> 编程语言
开源

适用于 RubyMotion 的简单模型和验证混合组件

189 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

适用于 RubyMotion 的简单模型和验证混合组件

MotionModel: Models, Relations, and Validation for RubyMotion

MotionModel is a DSL for cases where Core Data is too heavy to lift but you are still intending to work with your data, its types, and its relations. It also provides for data validation and actually quite a bit more.

File Module Description
ext.rb N/A Core Extensions that provide a few Rails-like niceties. Nothing new here, moving on...
model.rb MotionModel::Model You should read about it in "What Model Can Do". Model is the raison d'etre and the centerpiece of MotionModel.
validatable.rb MotionModel::Validatable Provides a basic validation framework for any arbitrary class. You can also create custom validations to suit your app's unique needs.
input_helpers MotionModel::InputHelpers Helps hook a collection up to a data form, populate the form, and retrieve the data afterwards. Note: MotionModel supports Formotion for input handling as well as these input helpers.
formotion.rb MotionModel::Formotion Provides an interface between MotionModel and Formotion
transaction.rb MotionModel::Model::Transactions Provides transaction support for model modifications

MotionModel is MIT licensed, which means you can pretty much do whatever you like with it. See the LICENSE file in this project.

  • Getting Going
  • Bugs, Features, and Issues, Oh My!
  • What Model Can Do
  • Model Data Types
  • Validation Methods
  • Model Instances and Unique IDs
  • Using MotionModel
  • Transactions and Undo/Cancel
  • Notifications
  • Core Extensions
  • Formotion Support
  • Problems/Comments
  • Submissions/Patches

Bugs, Features, and Issues, Oh My!

The reason this is up front here is that in order to respond to your issues we need you to help us out by reading these guidelines. You can also look at Submissions/Patches near the bottom of this README which restates a bit of this.

That said, all software has bugs, and anyone who thinks otherwise probably is smarter than I am. There are going to be edge cases or cases that our tests don't cover. And that's why open source is great: other people will run into issues we can fix. Other people will have needs we don't have but that are of general utility. And so on.

But… fair is fair. We would make the following requests of you:

  • Debug the code as far as you can. Obviously, there are times when you just won't be able to see what's wrong or where there's some squirrely interaction with RubyMotion.
  • If you are comfortable with the MotionModel code, please try to write a spec that makes it fail and submit a pull request with that failing spec. The isolated test case helps us narrow down what changed and to know when we have the issue fixed. Two things make this even better:
    1. Our specs become more comprehensive; and
    2. If the issue is an interaction between MotionModel and RubyMotion, it's easier to pass along to HipByte and have a spec they can use for a quick hitting test case. Even better, fix the bug and submit that fix and the spec in a pull request.
  • If you are not comfortable with the MotionModel code, then go ahead and describe the issue in as much detail as possible, including backtraces from the debugger, if appropriate.

Now, I've belabored the point about bug reporting enough. The point is, if you possibly can, write a spec.

Issues: Please mark your issues as questions or feature requests, depending on which they are. We'll do all we can to review them and answer questions as quickly as possible. For feature requests, you really can implement the feature in many cases and then submit a pull request. If not, we'll leave it open for consideration in future releases.

Summary

Bugs: Please write a failing spec

Issues: Please mark them as question or request

Changes for Existing Users to Be Aware Of

Please see the CHANGELOG for update on changes.

Version 0.4.4 is the first version to be gem-compatible with RubyMotion 2.0

Version 0.3.8 to 0.4.0 is a minor version bump, not a patch version. Upgrading to 0.4.0 will break existing code. To update your code, simply insert the following line:

ruby
class ModelWithAdapter
  include MotionModel::Model
  include MotionModel::ArrayModelAdapter #  'git@github.com:sxross/MotionModel.git'

Note that in the above construct, Ruby 1.8.x hash keys are used. That's because Apple's System Ruby is 1.8.7 and won't recognize keen new 1.9.x hash syntax.

What MotionModel Can Do

You can define your models and their schemas in Ruby. For example:

ruby
class Task
  include MotionModel::Model
  include MotionModel::ArrayModelAdapter

  columns :name        => :string,
          :long_name   => :string,
          :due_date    => :date
end

class MyCoolController
  def some_method
    @task = Task.create :name => 'walk the dog',
                :long_name    => 'get plenty of exercise. pick up the poop',
                :due_date     => '2012-09-15'
   end
end

Side note: The original documentation on this used description for the column that is now long_name. It turns out Apple reserves description so MotionModel saves you the trouble of finding that particular bug by not allowing you to use it for a column name.

Models support default values, so if you specify your model like this, you get defaults:

ruby
class Task
  include MotionModel::Model
  include MotionModel::ArrayModelAdapter

  columns :name     => :string,
          :due_date => {:type => :date, :default => '2012-09-15'}
end

A note on defaults, you can specify a proc, block or symbol for your default if you want to get fancy. The most obvious use case for this is that Ruby will optimize the assignment of an array so that a default of [] always points to the same object. Not exactly what is intended. Wrapping this in a proc causes a new array to be created. Here's an example:

class Foo
  include MotionModel::Model
  include MotionModel::ArrayModelAdapter
  columns  subject: { type: :array, default: ->{ [] } }
end

This is not constrained to initializing arrays. You can initialize pretty much anything using a proc or block. If you are specifying a block, make sure to use begin/end instead of do/end because it makes Ruby happy.

Here's a different example:

class Timely
  include MotionModel::Model
  include MotionModel::ArrayModelAdapter
  columns  ended_run_at: { type: :time, default: ->{ Time.now } }
end

Note that this uses the "stubby proc" syntax. That is pretty much equivalent to:

columns  ended_run_at: { type: :time, default: lambda { Time.now } }

for the previous example.

If you want to use a block, use the begin/end syntax:

columns  ended_run_at: { type: :time, default:
  begin
    Time.now
  end
  }

Finally, you can have the default call some class method as follows:

class Timely
  include MotionModel::Model
  include MotionModel::ArrayModelAdapter
  columns  unique_thingie: { type: :integer, default: :randomize }

  def self.randomize
    rand 1_000_000
  end
end

You can also include the Validatable module to get field validation. For example:

ruby
class Task
  include MotionModel::Model
  include MotionModel::ArrayModelAdapter
  include MotionModel::Validatable

  columns :name        => :string,
          :long_name   => :string,
          :due_date    => :date
  validates :name, :presence => true
end

class MyCoolController
  def some_method
    @task = Task.new :name  => 'walk the dog',
                 :long_name => 'get plenty of exercise. pick up the poop',
                 :due_date  => '2012-09-15'

    show_scary_warning unless @task.valid?
  end
end

Important Note: Type casting occurs at initialization and on assignment. That means If you have a field type int, it will be changed from a string to an integer when you initialize the object of your class type or when you assign to the integer field in your class.

ruby
a_task = Task.create(:name => 'joe-bob', :due_date => '2012-09-15')     # due_date is cast to NSDate

a_task.due_date = '2012-09-19'    # due_date is cast to NSDate

Model Data Types

Currently supported types are:

  • :string
  • :text
  • :boolean, :bool
  • :int, :integer
  • :float, :double
  • :date
  • :array

You are really not encouraged to stuff big things in your models, which is why a blob type is not implemented. The smaller your data, the less overhead involved in saving/loading.

Special Columns

The two column names, created_at and updated_at will be adjusted automatically if they are declared. They need to be of type :date. The created_at column will be set only when the object is created (i.e., on first save). The updated_at column will change every time the object is saved.

Validation Methods

To use validations in your model, declare your model as follows:

ruby
class MyValidatableModel
  include MotionModel::Model
  include MotionModel::ArrayModelAdapter
  include MotionModel::Validatable

  # All other model-y stuff here
end

Here are some sample validations:

validate :field_name, :presence => true
validate :field_name, :length => 5..8 # specify a range
validate :field_name, :email => true
validate :field_name, :format => /\A\d?\d-\d?\d-\d\d\Z/ # expected string format would be like '12-12-12'

The framework is sufficiently flexible that you can add in custom validators like so:

ruby
module MotionModel
  module Validatable
    def validate_foo(field, value, setting)
      # do whatever you need to make sure that the value
      # denoted by *value* for the field corresponds to
      # whatever is passed in setting.
    end
  end
end

validate  :my_field, :foo => 42

In the above example, your new validate_foo method will get the arguments pretty much as you expect. The value of the last hash is passed intact via the settings argument.

You are responsible for adding an error message using:

add_message(field, "incorrect value foo #{the_foo} -- should be something else.")

You must return true from your validator if the value passes validation otherwise false.

An important note about save once you include Validatable, you have two flavors of save:

Method Meaning
save(options) Just saves the data if it is valid (passes validations) or if you have specified :validate => false for options
save! Saves the data if it is valid, otherwise raises a MotionModel::Validatable::RecordInvalid exception

Model Instances and Unique IDs

It is assumed that models can be created from an external source (JSON from a Web application or NSCoder from the device) or simply be a stand-alone data store. To identify rows properly, the model tracks a special field called :id. If it's already present, it's left alone. If it's missing, then it is created for you. Each row id is guaranteed to be unique, so you can use this when communicating with a server or syncing your rowset to a UITableView.

Using MotionModel

  • Your data in a model is accessed in a very ActiveRecord (or Railsey) way. This should make transitioning from Rails or any ORM that follows the ActiveRecord pattern pretty easy. Some of the finder syntactic sugar is similar

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言