Permalink
Browse files

add in "instance methods" of a sort

Person find 'id=1' | Person first_name # => John
Person find 'id=1' | Person last_name # => Public

Person::full_name() {
  echo "$first_name $last_name"
}

Person find 'id=1' | Person full_name # => "John Public"

Hell yes.
  • Loading branch information...
1 parent cd4ca27 commit 29329e544c8ee71aa27901e5b0f78264815b68ac @jneen committed Mar 21, 2011
Showing with 39 additions and 4 deletions.
  1. +39 −4 lib/model.sh
View
@@ -10,13 +10,29 @@ balls::model::impl() {
if exists "$model.$mode"; then
"$model.$mode" "$@"
+ elif exists "$model::$mode"; then
+ while read line; do
+ balls::model.with "$line" "$model::$mode"
+ done
+ elif balls::model.fields | matches "^$mode\$"; then
+ balls::model.field "$mode"
elif exists "balls::model.$mode"; then
"balls::model.$mode" "$@"
else
stderr "oh no! couldn't find \`$model.$mode\`."
fi
}
+balls::model.with() {
+ local __data="$1"; shift
+ local __callback="$1"; shift
+ for __field in $(balls::model.fields); do
+ local "$__field"="$(balls::model.field "$__field" <<<"$__data\n")"
+ local "$__field"="$(balls::model.field "$__field" <<<"$__data\n")"
+ done
+ "$__callback" "$@"
+}
+
balls::model() {
alias "$1"="balls::model::impl $1"
}
@@ -25,10 +41,28 @@ balls::model.find() {
balls::model.execute "SELECT * from $(balls::model.table_name) WHERE $@"
}
-balls::model.column_names() {
+balls::model.fields() {
balls::model.execute "SHOW COLUMNS IN $(balls::model.table_name)" |\
- cut -f1 |\
- tail -n+2
+ cut -f1 # bah
+}
+
+balls::model.field_map() {
+ balls::model.fields | nl -nrz -ba
+}
+
+balls::model.column_number_for() {
+ local field="$1"
+ balls::model.field_map | grep "$field\$" | cut -f1
+}
+
+balls::model.field_at() {
+ local idx="$1"
+ balls::model.column_map | grep "^$idx" | cut -f2-
+}
+
+balls::model.field() {
+ local idx="$(balls::model.column_number_for "$1")"
+ cut -f"$idx"
}
balls::model.table_name() {
@@ -43,5 +77,6 @@ balls::model.table_name() {
}
balls::model.execute() {
- mysql $BALLS_DB_CREDENTIALS "$BALLS_DB" -e "$@" | cat
+ mysql $BALLS_DB_CREDENTIALS "$BALLS_DB" -e "$@" | tail -n+2 |\
+ sed 's/NULL//g'
}

0 comments on commit 29329e5

Please sign in to comment.