Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 54 lines (45 sloc) 1.955 kB
d036073 BossDB is now its own project
Evan Miller authored
1 -module(boss_record_lib).
2 -export([run_before_hooks/2,
3 run_after_hooks/3,
4 run_before_delete_hooks/1,
5 is_boss_record/2,
6 dummy_record/1,
7 attribute_names/1,
8 ensure_loaded/1]).
9
10 run_before_hooks(Record, true) ->
11 run_hooks(Record, element(1, Record), before_create);
12 run_before_hooks(Record, false) ->
13 run_hooks(Record, element(1, Record), before_update).
14
15 run_after_hooks(_UnsavedRecord, SavedRecord, true) ->
16 boss_news:created(SavedRecord:id(), SavedRecord:attributes()),
17 run_hooks(SavedRecord, element(1, SavedRecord), after_create);
18 run_after_hooks(UnsavedRecord, SavedRecord, false) ->
19 boss_news:updated(SavedRecord:id(), UnsavedRecord:attributes(), SavedRecord:attributes()),
20 run_hooks(SavedRecord, element(1, SavedRecord), after_update).
21
22 run_before_delete_hooks(Record) ->
23 run_hooks(Record, element(1, Record), before_delete).
24
25 run_hooks(Record, Type, Function) ->
26 case erlang:function_exported(Type, Function, 1) of
27 true -> Record:Function();
28 false -> ok
29 end.
30
31 is_boss_record(Record, ModelList) when is_tuple(Record) andalso is_atom(element(1, Record)) ->
32 Type = element(1, Record),
33 lists:member(atom_to_list(Type), ModelList) andalso
34 erlang:function_exported(Type, attribute_names, 1) andalso
35 erlang:function_exported(Type, new, tuple_size(Record) - 1);
36 is_boss_record(_, _) ->
37 false.
38
39 dummy_record(Module) ->
40 NumArgs = proplists:get_value('new', Module:module_info(exports)),
41 apply(Module, 'new', lists:map(fun(1) -> 'id'; (_) -> undefined end, lists:seq(1, NumArgs))).
42
43 attribute_names(Module) ->
44 DummyRecord = dummy_record(Module),
45 DummyRecord:attribute_names().
46
47 ensure_loaded(Module) ->
48 case code:ensure_loaded(Module) of
49 {module, Module} ->
50 Exports = Module:module_info(exports),
51 proplists:get_value(attribute_names, Exports) =:= 1;
52 _ -> false
53 end.
Something went wrong with that request. Please try again.