最近几天写了一个 Rails 后台自动化创建的 gem,名叫Carload(装满货物),它同Rails Admin
,ActiveAdmin
和Administrate
干的是同一件事,你要问我为啥不直接用那仨,我也说不出来,就是享受造轮子。
我尽可能把重复性工作封装起来,比如配置 Dashboard 使用如下简明的 DSL(我喜欢 DSL。。):
# Dashboard class is used to tell Carload what models are needed to administrated,
# which attributes are shown, etc.
class Dashboard < Carload::Dashboard
# There are two DSL block types:
#
# model :<model_name> do |spec|
# # Whether model should be displayed when URL does not specify one
# spec.default = <true_or_false>
# # List of attributes that can be edited
# spec.attributes.permitted = [...]
# # List of attributes that will be shown on index page
# spec.index_page.shows.attributes = [...]
# # List of attributes with search terms that can be searched on index page (using Ransack gem)
# spec.index_page.searches.attributes = [ { name: ..., term: ...}, ... ]
# end
#
# associate :<model_name_a> => :<model_name_b>, choose_by: :<attribute_in_model_b>
model :product do |spec|
spec.default = true
spec.attributes.permitted = [ :name ]
spec.index_page.shows.attributes = [ :name ]
spec.index_page.searches.attributes = [
{ name: :name, term: :cont }
]
end
model :item do |spec|
spec.attributes.permitted = [ :name, :product_id ]
spec.index_page.shows.attributes = [ :name, 'product.name' ]
spec.index_page.searches.attributes = [
{ name: :name, term: :cont },
{ name: 'product.name', term: :cont }
]
end
associate :item => :product, choose_by: :name
end
然后 Carload 就会为你准备如下后台:
并且还会处理错误哦:
搜索用的是 Ransack,切页用的是 Kaminari,权限管理用的是 Pundit,所以一切都要自动化起来!不过如果你对页面不满意,需要定制,也是可以的,直接在app/views/dashboard/<model_names>/
目录下创建相应的 erb 文件就行,动作遵循 Rails 规范。
欢迎大家一起来造轮子!演示戳这里。
更新:
在一定假设条件下可以上传图片了:
carrierwave
image
,logo
或img
这些假设可以慢慢放宽,不过目前先 enjoy 这些吧:
TODO List