diff --git a/solutions/sinatra_resource/members.rb b/solutions/sinatra_resource/members.rb new file mode 100644 index 0000000..482c177 --- /dev/null +++ b/solutions/sinatra_resource/members.rb @@ -0,0 +1,111 @@ +require "sinatra" + +class Member + attr_reader :name + + def initialize(name = nil) + @name = name + end +end + +class MemberValidator + attr_reader :name, :names, :messages + + def initialize(name, names) + @name = name.to_s + @names = names + @messages = [] + end + + def valid? + validate + messages.empty? + end + + private + + def validate + if name.empty? + messages << "You need to enter a name" + elsif names.include?(name) + messages << "#{name} is already included in our list." + end + end +end + +FILENAME = "names.txt" + +def members + names.map { |name| Member.new(name) } +end + +def names + return [] unless File.exists?(FILENAME) + File.read(FILENAME).split("\n") +end + +def find_member(name) + members.detect { |member| member.name == name } +end + +def add_member(name) + File.open(FILENAME, "a+") do |file| + file.puts(name) + end +end + +def remove_member(name) + lines = names.reject { |other| name == other } + + File.open(FILENAME, "w+") do |file| + file.puts(lines.join("\n")) + end +end + +get "/members" do + @members = members + erb :index +end + +get "/members/new" do + @member = Member.new + erb :new +end + +post "/members" do + name = params[:name] + validator = MemberValidator.new(name, names) + + if validator.valid? + add_member(name) + redirect "/members/#{name}" + else + @member = Member.new(name) + @messages = validator.messages + erb :new + end +end + +get "/members/:name" do + @member = find_member(params[:name]) + erb :show +end + +get "/members/:name/edit" do + @member = find_member(params[:name]) + erb :edit +end + +put "/members/:name" do + @member = find_member(params[:name]) +end + +get "/members/:name/delete" do + @member = find_member(params[:name]) + erb :delete +end + +delete "/members/:name" do + remove_member(params[:name]) + redirect "/members" +end diff --git a/solutions/sinatra_resource/names.txt b/solutions/sinatra_resource/names.txt new file mode 100644 index 0000000..d2e58da --- /dev/null +++ b/solutions/sinatra_resource/names.txt @@ -0,0 +1,5 @@ +Anja +Carla +Maren +Rebecca +Sabrina diff --git a/solutions/sinatra_resource/views/delete.erb b/solutions/sinatra_resource/views/delete.erb new file mode 100644 index 0000000..7cc18ad --- /dev/null +++ b/solutions/sinatra_resource/views/delete.erb @@ -0,0 +1,13 @@ +
+ All Members | + <%= @member.name %> +
+ +Are you sure you want to remove the member <%= @member.name %>?
+ + diff --git a/solutions/sinatra_resource/views/edit.erb b/solutions/sinatra_resource/views/edit.erb new file mode 100644 index 0000000..fd3c7c6 --- /dev/null +++ b/solutions/sinatra_resource/views/edit.erb @@ -0,0 +1,12 @@ ++ All Members | + <%= @member.name %> +
+ +Name: <%= @member.name %>