wings-framework 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c2c44038b9a7411598ec1c2b8ea1ce12a4030ef763ea5a089e988d82286e18ae
4
+ data.tar.gz: 7d538345525beee6416b3a9e38c17ebb41ab903e23444b9c0d7a151e9712e79c
5
+ SHA512:
6
+ metadata.gz: 3407d511155727ecbdc1911955c1392c4d47f1d8bb79a471179c463634c346a0ad9e873d9eddc74f93f5ab61cc94513244151efd6ced413747727a1a4f894794
7
+ data.tar.gz: ace97efea23ca212bbfdb78effde447cb6882c755eb09da2644a485591785d3f613564c76d427fad4c0a3985ffd5272d475c0897cff60178650d3a6344f62941
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ /.idea/
10
+ debug.txt
11
+ *.gem
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at jinghua.shih@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in wings.gemspec
4
+ gemspec
@@ -0,0 +1,41 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ wings (0.0.6)
5
+ erubis (~> 2.7)
6
+ multi_json (~> 1.11)
7
+ rack (>= 1.6.4)
8
+ sqlite3 (~> 1.3)
9
+
10
+ GEM
11
+ remote: https://rubygems.org/
12
+ specs:
13
+ coderay (1.1.2)
14
+ erubis (2.7.0)
15
+ method_source (0.9.2)
16
+ minitest (5.11.3)
17
+ multi_json (1.13.1)
18
+ pry (0.12.2)
19
+ coderay (~> 1.1.0)
20
+ method_source (~> 0.9.0)
21
+ rack (2.0.7)
22
+ rack-test (1.1.0)
23
+ rack (>= 1.0, < 3)
24
+ rake (10.5.0)
25
+ rr (1.2.1)
26
+ sqlite3 (1.4.1)
27
+
28
+ PLATFORMS
29
+ ruby
30
+
31
+ DEPENDENCIES
32
+ bundler (~> 2.0)
33
+ minitest (~> 5.0)
34
+ pry (~> 0.12.2)
35
+ rack-test (~> 1.1)
36
+ rake (~> 10.0)
37
+ rr (~> 1.2)
38
+ wings!
39
+
40
+ BUNDLED WITH
41
+ 2.0.2
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 jennyshih
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,144 @@
1
+ # Ruby on Wings
2
+
3
+ ## A Bird Eye's View of Wings Structure
4
+ ![wings structure](https://user-images.githubusercontent.com/43872616/64002900-bd3f5a00-cb3d-11e9-9e6a-d22202389b2d.png)
5
+
6
+ For now the `Wings::Model` module includes `FileModel` and `SQLite` classes.
7
+
8
+ ## Usage
9
+ ### Wings::Application
10
+
11
+ ```ruby
12
+ # your_app/config/application.rb
13
+
14
+ require 'wings'
15
+
16
+ # loading controllers
17
+ $LOAD_PATH << File.join(File.dirname(__FILE__), '..', 'app', 'controllers')
18
+
19
+ module YourApp
20
+ class Application < Wings::Application
21
+ end
22
+ end
23
+ ```
24
+
25
+ ### Wings::Router
26
+
27
+ ```ruby
28
+ # your_app/config.ru
29
+
30
+ require './config/application'
31
+
32
+ app = YourApp::Application.new
33
+
34
+ app.route do
35
+ # route for the root path ('/'), format: '[controller#action]
36
+ root 'examples#index'
37
+
38
+ # REST style routes mapping,
39
+ # creating routes for [:index, :new, :create, :edit, :show, :update, :destroy]
40
+ # options: [:only, :except]
41
+ resources :examples, only: [:index, :create, :show]
42
+
43
+ # standalone route matching
44
+ match 'an_example', to: 'examples#an_example'
45
+ match 'good_ones/:id', to: 'another_controller#show'
46
+ end
47
+
48
+ run app
49
+ ```
50
+ - **Auto Routing**: Wings provides the following three default route matching rules:
51
+
52
+ ```ruby
53
+ match ':controller/:id/:action'
54
+ match ':controller/:id', 'action' => 'show'
55
+ match ':controller', 'action' => 'index'
56
+ ```
57
+
58
+ ### Wings::Model
59
+ Models are put into `app/models/` directory.
60
+
61
+ Wings supports two types of models: `FileModel` and `SQLite`. Below is an example of creating an `Example` model with `SQLite`.
62
+
63
+ #### step 1: creating a SQLite database
64
+ We do this by manually creating a migration file first. It creates a connection to the database in `db/[your_project].db` and then a table named `example`.
65
+
66
+ ```ruby
67
+ require 'sqlite3'
68
+
69
+ conn = SQLite3::Database.new('db/your_project.db')
70
+ conn.execute <<SQL
71
+ create table example (
72
+ id INTEGER PRIMARY KEY,
73
+ column1 VARCHAR(32000),
74
+ column2 VARCHAR(100)
75
+ );
76
+ SQL
77
+ ```
78
+ Run this migration file.
79
+ #### step 2
80
+ Create a new file at `your_app/app/models/example.rb`
81
+
82
+ ```ruby
83
+ # your_app/app/models/example.rb
84
+
85
+ class Example < Wings::Model::SQLite
86
+ end
87
+ ```
88
+ And you're good to go!
89
+
90
+ - **ORM**: `Wings::Model::SQLite` comes with a basic ORM (Object Relational Mapping), which allows you to manipulate your database objects like Ruby objects, with Ruby code. Right now the module supports
91
+ - `create`: insert a row in a database table.
92
+ - `find`: find a specific row with id.
93
+ - `all`: get all rows in the table.
94
+ - attribute accessor/writer: each attribute is a hash key in the database object. You can read it as well as set it, and use `save!` or `save` method to update the database.
95
+
96
+ Examples can be found in the following section.
97
+
98
+ ### Wings::Controller
99
+ Controllers are put into `app/controllers/` directory.
100
+
101
+ ```ruby
102
+ # your_app/app/controllers/examples_controller.rb
103
+
104
+ Class ExamplesController < Wings::Controller
105
+ def index
106
+ @examples = Example.all
107
+ end
108
+
109
+ def create
110
+ @example = Example.create(**params['example'])
111
+
112
+ render :show
113
+ end
114
+
115
+ def show
116
+ @example = Example.find(params['id'])
117
+ end
118
+
119
+ def an_example
120
+ end
121
+ end
122
+ ```
123
+
124
+ - **Auto Template Rendering**: If `render` isn't called in the action, Wings will locate the view template in `app/views/[controller]/[view].html.erb`.
125
+ - **Auto Instance Variable Passing**: Instance variables in the controller will be passed to its corresponding template automatically.
126
+
127
+
128
+ ## Development
129
+
130
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
131
+
132
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
133
+
134
+ ## Contributing
135
+
136
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jing-jenny-shih/wings. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
137
+
138
+ ## License
139
+
140
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
141
+
142
+ ## Code of Conduct
143
+
144
+ Everyone interacting in the Wings project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/jing-jenny-shih/wings/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "wings"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,28 @@
1
+ require 'wings/util'
2
+ require 'wings/version'
3
+ require 'wings/routing'
4
+ require 'wings/controller'
5
+ require 'wings/file_model'
6
+ require 'wings/dependencies'
7
+
8
+ module Wings
9
+ class Application
10
+ def call(env)
11
+ rack_app = get_rack_app(env)
12
+ rack_app.call(env)
13
+ end
14
+
15
+ def route(&block)
16
+ @route_obj ||= Route.new
17
+ @route_obj.instance_eval(&block)
18
+ end
19
+
20
+ private
21
+
22
+ def get_rack_app(env)
23
+ raise 'No routes!' unless @route_obj
24
+
25
+ @route_obj.check_url(env['PATH_INFO'], env['REQUEST_METHOD'])
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,73 @@
1
+ require 'wings/view'
2
+ require 'wings/file_model'
3
+ require 'wings/sqlite_model'
4
+
5
+ module Wings
6
+ class Controller
7
+ Dir["app/models/*.rb"].each { |file| require "#{Dir.pwd}/#{file}" }
8
+ include Wings::Model
9
+
10
+ attr_reader :env, :request, :params, :response
11
+
12
+ # Respond to Rack
13
+ # The action will be used like a Rack app
14
+ def self.action(act, rp = {})
15
+ proc { |e| self.new(e).dispatch(act, rp) }
16
+ end
17
+
18
+ def initialize(env)
19
+ @env = env
20
+ @request = Rack::Request.new(env)
21
+ @params = request.params
22
+ end
23
+
24
+ def dispatch(action, routing_params = {})
25
+ @params.merge!(routing_params)
26
+
27
+ self.send(action)
28
+
29
+ if response
30
+ [response.status, response.headers, response.body]
31
+ else
32
+ render(action)
33
+ end
34
+ end
35
+
36
+ # [options for render]
37
+ # locals: local variables
38
+ # status: status code
39
+ # headers: headers
40
+ def render(template, **opts)
41
+ raise 'You can only render once!' if @response
42
+
43
+ v = View.new(params_for_view(template, opts))
44
+ @response = Rack::Response.new(v.text, v.status, v.headers)
45
+ end
46
+
47
+ private
48
+
49
+ def params_for_view(template, opts = {})
50
+ {
51
+ env: env,
52
+ status: opts[:status],
53
+ headers: opts[:headers],
54
+ template: template,
55
+ local_vars: opts[:locals],
56
+ controller: controller_name,
57
+ instance_vars: instance_variable_hash,
58
+ }
59
+ end
60
+
61
+ def controller_name
62
+ klass = self.class.to_s.gsub(/Controller$/, '')
63
+ Wings.to_underscore klass
64
+ end
65
+
66
+ def instance_variable_hash
67
+ self.instance_variables.reduce({}) do |memo, var|
68
+ memo[var] = self.instance_variable_get(var)
69
+ memo
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,12 @@
1
+ class Object
2
+ def self.const_missing(c)
3
+ super if @calling_const_missing
4
+
5
+ @calling_const_missing = true
6
+ require Wings.to_underscore(c.to_s)
7
+ klass = Object.const_get(c)
8
+ @calling_const_missing = false
9
+
10
+ klass
11
+ end
12
+ end
@@ -0,0 +1,65 @@
1
+ require 'multi_json'
2
+
3
+ module Wings
4
+ module Model
5
+ class FileModel
6
+ def initialize(filename)
7
+ @filename = filename
8
+
9
+ # if filename is 'dir/3.json', @id would be 3
10
+ @id = File.basename(filename, '.json').to_i
11
+ @data = MultiJson.load(File.read(filename))
12
+ end
13
+
14
+ def [](name)
15
+ @data[name.to_s]
16
+ end
17
+
18
+ def []=(name, value)
19
+ @data[name.to_s] = value
20
+ end
21
+
22
+ def self.find(id)
23
+ begin
24
+ FileModel.new("db/quotes/#{id}.json") # FIX
25
+ rescue
26
+ nil
27
+ end
28
+ end
29
+
30
+ def self.all
31
+ Dir['db/quotes/*.json'].map { |f| FileModel.new(f) }
32
+ end
33
+
34
+ def self.create(**attrs)
35
+ data = {
36
+ quote: attrs[:quote],
37
+ submitter: attrs[:submitter],
38
+ attribution: attrs[:attribution],
39
+ }
40
+
41
+ files = Dir['db/quotes/*.json']
42
+ existing_ids = files.map { |f| File.basename(f, '.json').to_i }
43
+ new_id = existing_ids.max + 1
44
+
45
+ File.open("db/quotes/#{new_id}.json", 'w') do |f|
46
+ f.write formatted_data(data)
47
+ end
48
+
49
+ FileModel.new "db/quotes/#{new_id}.json"
50
+ end
51
+
52
+ private
53
+
54
+ def self.formatted_data data
55
+ <<TEMPLATE
56
+ {
57
+ "quote": "#{data[:quote]}",
58
+ "submitter": "#{data[:submitter]}",
59
+ "attribution": "#{data[:attribution]}"
60
+ }
61
+ TEMPLATE
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,126 @@
1
+ module Wings
2
+ class Route
3
+ def initialize
4
+ @rules = []
5
+ end
6
+
7
+ def root(dest)
8
+ @rules.push(
9
+ {
10
+ regex: Regexp.new("^/?$"),
11
+ options: { to: dest, verb: :GET },
12
+ }
13
+ )
14
+ end
15
+
16
+ # actions: `index`, `new`, `create`, `show`, `edit`, `update`, `destroy`
17
+ def resources(obj, **options)
18
+ actions = {
19
+ index: { path: "#{obj}" },
20
+ new: { path: "#{obj}/new" },
21
+ create: { path: "#{obj}", verb: :POST },
22
+ show: { path: "#{obj}/:id" },
23
+ edit: { path: "#{obj}/:id/edit" },
24
+ update: { path: "#{obj}/:id", verb: :PATCH },
25
+ destroy: { path: "#{obj}/:id", verb: :DELETE },
26
+ }
27
+
28
+ if options[:only]
29
+ options[:only].each do |action|
30
+ match actions[action][:path], to: "#{obj}##{action}", verb: actions[action][:verb]
31
+ end
32
+ elsif options[:except]
33
+ actions.each do |action, value|
34
+ next if options[:except].include?(action)
35
+
36
+ match value[:path], to: "#{obj}##{action}", verb: value[:verb]
37
+ end
38
+ else
39
+ actions.each do |action, value|
40
+ match value[:path], to: "#{obj}##{action}", verb: value[:verb]
41
+ end
42
+ end
43
+ end
44
+
45
+ def match(url, **opts)
46
+ vars = []
47
+ regex = url.split('/')
48
+ .reject { |pt| pt.empty? }
49
+ .map do |part|
50
+ if part[0] == ':'
51
+ vars << part[1..-1]
52
+ '([a-zA-Z0-9]+)'
53
+ elsif part[0] == '*'
54
+ vars << part[1..-1]
55
+ '(.*)'
56
+ else
57
+ part
58
+ end
59
+ end.join('/')
60
+
61
+ opts[:verb] ||= :GET
62
+
63
+ @rules.push(
64
+ {
65
+ regex: Regexp.new("^/#{regex}/?$"),
66
+ options: opts,
67
+ vars: vars,
68
+ }
69
+ )
70
+ end
71
+
72
+ def check_url(url, req_method)
73
+ (@rules + default_matches).each do |r|
74
+ m = r[:regex].match(url)
75
+ params = r[:options].dup
76
+
77
+ next unless m
78
+ next unless req_method == params[:verb].to_s
79
+
80
+ if vars = r[:vars]
81
+ vars.each_with_index do |v, i|
82
+ params[v] = m.captures[i]
83
+ end
84
+ end
85
+
86
+ dest = params[:to] || "#{params['controller']}##{params['action']}"
87
+ return get_destination(dest, params)
88
+ end
89
+
90
+ nil
91
+ end
92
+
93
+ private
94
+
95
+ def default_matches
96
+ [
97
+ {
98
+ regex: Regexp.new('^/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/?$'),
99
+ vars: %w( controller id action ),
100
+ options: { verb: :GET },
101
+ },
102
+ {
103
+ regex: Regexp.new('^/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/?$'),
104
+ vars: %w( controller id ),
105
+ options: { verb: :GET, 'action' => 'show' },
106
+ },
107
+ {
108
+ regex: Regexp.new('^/([a-zA-Z0-9]+)/?$'),
109
+ vars: %w( controller ),
110
+ options: { verb: :GET, 'action' => 'index' },
111
+ },
112
+ ]
113
+ end
114
+
115
+ def get_destination(dest, routing_params = {})
116
+ return dest if dest.respond_to?(:call)
117
+
118
+ if dest =~ /^([^#]+)#([^#]+)$/
119
+ cont = Object.const_get("#{$1.capitalize}Controller")
120
+ return cont.action($2, routing_params)
121
+ end
122
+
123
+ raise "No destination: #{dest.inspect}!"
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,138 @@
1
+ require 'sqlite3'
2
+ require 'wings/util'
3
+
4
+
5
+ module Wings
6
+ module Model
7
+ class SQLite
8
+ def self.create(values)
9
+ keys_without_id = schema.keys - ['id']
10
+
11
+ db_attributes = keys_without_id.reduce({}) do |memo, key|
12
+ memo[key] = values[key] ? to_sql(values[key]) : 'null'
13
+ memo
14
+ end
15
+
16
+ db.execute <<SQL
17
+ INSERT INTO #{table} (#{db_attributes.keys.join(',')})
18
+ VALUES (#{db_attributes.values.join(',')});
19
+ SQL
20
+
21
+ data = keys_without_id.reduce({}) do |memo, key|
22
+ memo[key] = values[key]
23
+ memo
24
+ end
25
+ data['id'] = db.execute('SELECT last_insert_rowid();')[0][0]
26
+ self.new(data)
27
+ end
28
+
29
+ def self.find(id)
30
+ target = db.execute <<SQL
31
+ SELECT * FROM #{table} WHERE id = #{id};
32
+ SQL
33
+
34
+ data = Hash[schema.keys.zip(target[0])]
35
+ self.new(data)
36
+ end
37
+
38
+ def self.all
39
+ all_rows = db.execute <<SQL
40
+ SELECT * FROM #{table};
41
+ SQL
42
+
43
+ all_rows.map do |row|
44
+ data = Hash[schema.keys.zip(row)]
45
+ self.new(data)
46
+ end
47
+ end
48
+
49
+ def self.count
50
+ sql = <<SQL
51
+ SELECT COUNT(*) FROM #{table};
52
+ SQL
53
+ db.execute(sql)[0][0]
54
+ end
55
+
56
+ def self.schema
57
+ return @schema if @schema
58
+
59
+ @schema = {}
60
+ db.table_info(table) do |row|
61
+ @schema[row['name']] = row['type']
62
+ end
63
+ @schema
64
+ end
65
+
66
+ def initialize(data = nil)
67
+ @data = data
68
+ end
69
+
70
+ def [](name)
71
+ @data[name.to_s]
72
+ end
73
+
74
+ def []=(name, value)
75
+ @data[name.to_s] = value
76
+ end
77
+
78
+ def save!
79
+ unless @data['id']
80
+ self.class.create(@data)
81
+ return true
82
+ end
83
+
84
+ fields = @data.map do |key, value|
85
+ "#{key}=#{self.class.to_sql(value)}"
86
+ end.join(',')
87
+
88
+ self.class.db.execute <<SQL
89
+ UPDATE #{self.class.table}
90
+ SET #{fields}
91
+ WHERE id = #{@data['id']};
92
+ SQL
93
+
94
+ true
95
+ end
96
+
97
+ def save
98
+ self.save! rescue false
99
+ end
100
+
101
+ # column accessor
102
+ def method_missing(name, *args)
103
+ unless self.class.schema.keys.include?(name.to_s)
104
+ return super
105
+ end
106
+
107
+ self.class.define_method(name.to_sym) do
108
+ @data[name.to_s]
109
+ end
110
+ @data[name.to_s]
111
+ end
112
+
113
+ private
114
+
115
+ def self.db
116
+ project_name = Dir.pwd.split('/').last
117
+ @@db ||= SQLite3::Database.new("db/#{project_name}.db")
118
+ end
119
+
120
+ def self.table
121
+ Wings.to_underscore name
122
+ end
123
+
124
+ def self.to_sql(val)
125
+ case val
126
+ when NilClass
127
+ 'null'
128
+ when Numeric
129
+ val.to_s
130
+ when String
131
+ "'#{val}'"
132
+ else
133
+ raise "Can't change #{val.class} to SQL. Bummer."
134
+ end
135
+ end
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,10 @@
1
+ module Wings
2
+ def self.to_underscore(string)
3
+ string
4
+ .gsub(/::/, '/')
5
+ .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
6
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
7
+ .tr('-', '_')
8
+ .downcase
9
+ end
10
+ end
@@ -0,0 +1,3 @@
1
+ module Wings
2
+ VERSION = '0.1.1'
3
+ end
@@ -0,0 +1,35 @@
1
+ require 'erubis'
2
+
3
+ module Wings
4
+ class View
5
+ attr_reader :text, :status, :headers
6
+
7
+ def initialize(attrs)
8
+ @env = attrs[:env]
9
+ @headers = attrs[:headers] || {}
10
+ @template = attrs[:template]
11
+ @local_vars = attrs[:local_vars] || {}
12
+ @controller = attrs[:controller]
13
+ @instance_vars = attrs[:instance_vars] || {}
14
+
15
+ @text = get_text
16
+ @status = attrs[:status] || 200
17
+ @headers['Content-Type'] ||= 'text/html'
18
+ end
19
+
20
+ private
21
+
22
+ def get_text
23
+ template = File.read(File.join('app', 'views', @controller, "#{@template}.html.erb"))
24
+ erb = Erubis::Eruby.new(template)
25
+ erb.result additional_variables
26
+ end
27
+
28
+ def additional_variables
29
+ Hash.new
30
+ .merge(env: @env)
31
+ .merge(@local_vars)
32
+ .merge(@instance_vars)
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,39 @@
1
+ lib = File.expand_path('lib', __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require 'wings/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'wings-framework'
7
+ spec.version = Wings::VERSION
8
+ spec.authors = ['Jenny Shih']
9
+ spec.email = ['jinghua.shih@gmail.com']
10
+
11
+ spec.summary = 'a Rack-based web framework inspired by Rails, with abridged functionality and a better name.'
12
+ spec.description = 'Wings is a Rack-based, MVC framework with REST implementation, also supports ORM for database manipulation.'
13
+ spec.homepage = 'https://github.com/jing-jenny-shih/wings'
14
+ spec.license = 'MIT'
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = 'https://github.com/jing-jenny-shih/wings'
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.bindir = 'exe'
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ['lib']
27
+
28
+ spec.add_development_dependency 'rack-test', '~> 1.1'
29
+ spec.add_development_dependency 'minitest', '~> 5.0'
30
+ spec.add_development_dependency 'bundler', '~> 2.0'
31
+ spec.add_development_dependency 'rake', '~> 10.0'
32
+ spec.add_development_dependency 'pry', '~> 0.12.2'
33
+ spec.add_development_dependency 'rr', '~> 1.2'
34
+
35
+ spec.add_runtime_dependency 'multi_json', '~> 1.11'
36
+ spec.add_runtime_dependency 'sqlite3', '~> 1.3'
37
+ spec.add_runtime_dependency 'erubis', '~> 2.7'
38
+ spec.add_runtime_dependency 'rack', '>= 1.6.4'
39
+ end
metadata ADDED
@@ -0,0 +1,207 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: wings-framework
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - Jenny Shih
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-08-31 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rack-test
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.1'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: minitest
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '5.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '5.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pry
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: 0.12.2
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: 0.12.2
83
+ - !ruby/object:Gem::Dependency
84
+ name: rr
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.2'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.2'
97
+ - !ruby/object:Gem::Dependency
98
+ name: multi_json
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '1.11'
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '1.11'
111
+ - !ruby/object:Gem::Dependency
112
+ name: sqlite3
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '1.3'
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '1.3'
125
+ - !ruby/object:Gem::Dependency
126
+ name: erubis
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - "~>"
130
+ - !ruby/object:Gem::Version
131
+ version: '2.7'
132
+ type: :runtime
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - "~>"
137
+ - !ruby/object:Gem::Version
138
+ version: '2.7'
139
+ - !ruby/object:Gem::Dependency
140
+ name: rack
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: 1.6.4
146
+ type: :runtime
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ">="
151
+ - !ruby/object:Gem::Version
152
+ version: 1.6.4
153
+ description: Wings is a Rack-based, MVC framework with REST implementation, also supports
154
+ ORM for database manipulation.
155
+ email:
156
+ - jinghua.shih@gmail.com
157
+ executables: []
158
+ extensions: []
159
+ extra_rdoc_files: []
160
+ files:
161
+ - ".gitignore"
162
+ - CODE_OF_CONDUCT.md
163
+ - Gemfile
164
+ - Gemfile.lock
165
+ - LICENSE.txt
166
+ - README.md
167
+ - Rakefile
168
+ - bin/console
169
+ - bin/setup
170
+ - lib/wings.rb
171
+ - lib/wings/controller.rb
172
+ - lib/wings/dependencies.rb
173
+ - lib/wings/file_model.rb
174
+ - lib/wings/routing.rb
175
+ - lib/wings/sqlite_model.rb
176
+ - lib/wings/util.rb
177
+ - lib/wings/version.rb
178
+ - lib/wings/view.rb
179
+ - wings.gemspec
180
+ homepage: https://github.com/jing-jenny-shih/wings
181
+ licenses:
182
+ - MIT
183
+ metadata:
184
+ homepage_uri: https://github.com/jing-jenny-shih/wings
185
+ source_code_uri: https://github.com/jing-jenny-shih/wings
186
+ post_install_message:
187
+ rdoc_options: []
188
+ require_paths:
189
+ - lib
190
+ required_ruby_version: !ruby/object:Gem::Requirement
191
+ requirements:
192
+ - - ">="
193
+ - !ruby/object:Gem::Version
194
+ version: '0'
195
+ required_rubygems_version: !ruby/object:Gem::Requirement
196
+ requirements:
197
+ - - ">="
198
+ - !ruby/object:Gem::Version
199
+ version: '0'
200
+ requirements: []
201
+ rubyforge_project:
202
+ rubygems_version: 2.7.6.2
203
+ signing_key:
204
+ specification_version: 4
205
+ summary: a Rack-based web framework inspired by Rails, with abridged functionality
206
+ and a better name.
207
+ test_files: []