首页
/ 推荐开源项目:Dish!

推荐开源项目:Dish!

2024-05-22 05:21:14作者:昌雅子Ethen

Dish Logo

Dish是一个极其简洁的工具,用于将哈希(Hash)转换为纯Ruby对象,特别适合于消费JSON API。此外,它还支持RubyMotion,让你在开发iOS应用时也能轻松处理JSON数据。

安装

只需在你的Gemfile中添加以下行:

gem "dish"

然后运行:

$ bundle

或者直接安装:

$ gem install dish

若要为Hash和Array对象添加to_dish辅助方法,可以在Gemfile中要求加载dish/ext

gem "dish", require: "dish/ext"

在RubyMotion中的安装

RubyMotion的用户可以这样安装Dish:

gem "dish", require: "dish/motion"

运行bundle后即可使用。

注意:如果你在使用Dish与BubbleWrap的JSON模块,请参阅项目文档以获取更多信息。

使用示例

hash = {
  title: "My Title",
  authors: [
    { id: 1, name: "Mike Anderson" },
    { id: 2, name: "Well D." }
  ],
  active: false
}

book = Dish(hash)
book.title           # => "My Title"
book.authors.length  # => 2
book.authors[1].name # => "Well D."
book.title?          # => true
book.active?         # => false
book.other           # => nil
book.other?          # => false

类型转换

Dish允许自动类型转换,如将值转换为自定义的Dish::Plate对象或Time对象,例如处理JSON源中的updated_at字段。

class Author < Dish::Plate; end

class Product < Dish::Plate
  coerce :updated_at, ->(value) { Time.parse(value) }
  coerce :authors, Author
end

source_products = [
  # ...
]
products = Dish(source_products, Product)
products.first.updated_at    # => Time对象 (例如2013-01-28 13:23:11)
products.first.authors.first # => Author对象

# 如果已引入"dish/ext",还可以这样操作:
products = source_products.to_dish(Product)

这受到了Hashie库中类型转换方法的启发。

尽情享受吧!

转换回Ruby/JSON对象

你可以使用Dish::Plate#to_h方法来访问原始哈希。同时,如果正在使用RubyMotion(使用NSJSONSerialization)或已加载了"json" Ruby标准库,也可以使用Dish::Plate#to_json方法进行JSON序列化。

注意:以前Dish::Plate#to_h被称为Dish::Plate#as_hash,现在Dish::Plate#as_hash已经废弃。

注意事项

与BubbleWrap JSON模块一起使用

当使用BubbleWrap解析JSON到哈希时,不能直接使用Hash#to_dish,因为BW::JSON返回的是非真实哈希对象。但可以通过以下方式实现相同效果:

BW::HTTP.get("http://path.to/api/books/2") do |response|
  json = BW::JSON.parse(response.body.to_s)
  book = Dish(json)

  title_label.text = book.title
  author_label.text = book.authors.map(&:name).join(", ")
end

贡献代码

欢迎加入新功能,但在提交之前,请先创建问题讨论。谢谢!

  1. 叉项目
  2. 创建特性分支(git checkout -b my-new-feature)
  3. 编码并添加测试确保不会破坏现有功能
  4. 提交更改(git commit -am 'Add feature')
  5. 推送到远程分支(git push origin my-new-feature)
  6. 创建拉取请求

现在,你已经了解了Dish,为何不尝试将其应用于你的项目呢?无论你是JSON API消费者还是RubyMotion开发者,Dish都是一个值得信赖的工具,其简洁的API和强大的类型转换功能定会给你带来便利。立即开始使用Dish,感受它带来的高效开发体验吧!

登录后查看全文
热门项目推荐