写了几个月的Rails,终于开始把项目移植到erlyweb,这个笔记将记录移植过程中的一些常见问题,主要是Rails和erlyweb的同与不同。
1. 怎样处理params
Rails:
erlyweb:
mymodel_controller.erl:
在apps/myapps/lib下写了一个yaws_params.erl:
[To be continued]
1. 怎样处理params
Rails:
ruby 代码
:p, "1")
s = params.fetch(:s, @@RECORDS_PER_PAGE)
p = p.to_i s = s.to_i
p = params.fetch(s = params.fetch(:s, @@RECORDS_PER_PAGE)
p = p.to_i s = s.to_i
erlyweb:
mymodel_controller.erl:
js 代码
- -module(mymodel_controller).
- -define(RECORDS_PER_PAGE, "9").
- -export([get/1]).
- get(A) ->
- %% A是yaws传进来的Arg, 包含了用户请求的所有内容
- P = yaws_params:getopt("p", A, "1"),
- S = yaws_params:getopt("s", A, ?RECORDS_PER_PAGE),
- Page = list_to_integer(P), %% erlang里String就是list
- Size = list_to_integer(S),
- %% 查找表mymodel的记录
- Records = mymodel:find_range((Page - 1) * Size, Size),
- %% 返回plain text形式的记录
- {response, [{html, mymodel:to_iolist(Records)}]}.
在apps/myapps/lib下写了一个yaws_params.erl:
js 代码
export([ getopt/2, getopt/3 ]). getopt(Key, Arg) -> getopt(Key, Arg, undefined). %% ruby里有nil, erlang里有undefined %% Usage: getopt(Key, Arg, Default) getopt(Key, Arg, Default) -> Params = yaws_api:parse_query(Arg), %% in form of [{p, "2"}, {s, "1"}] etc. case lists:keysearch(Key, 1, Params) of false -> Default; {value, Tuple} -> Val = element(2, Tuple), %% erlang里element从1开始计数 if Val == undefined -> Default; true -> Val end end.
-module(yaws_params). -[To be continued]