Sha256: da2239f261308e87b4d440d6d65134cab4d062b5d2429461e25ec4fa0fe0817d

Contents?: true

Size: 1.54 KB

Versions: 3

Compression:

Stored size: 1.54 KB

Contents

require 'json'
require 'yaml'

module ShnaiderCode
    class StudentsListFormatStrategy
        def read_from(filename)
            require 'method not implemented'
        end

        def write_to(filename, students)
            require 'method not implemented'
        end
    end

    class TxtStudentsListFormatStrategy < StudentsListFormatStrategy
        def read_from(filename)
            File.read(filename)
            .split("\n")
            .map { |v| Student.from_string(v) }
        end

        def write_to(filename, students)
            File.open(filename, 'w') { |file| 
                file.write(
                    students.map { |student| 
                        student.get_info
                    }
                    .join("\n")
                )
            }
        end
    end

    class JsonStudentsListFormatStrategy < StudentsListFormatStrategy
        def read_from(filename)
            file = File.read(filename)
            json = JSON.parse(file)
            json.map { |x| Student.from_json(x) }
        end

        def write_to(filename, students)
            File.open(filename, 'w') do |f|
                f.write(JSON.generate(students.map { |x| x.as_json }))
            end
        end
    end

    class YamlStudentsListFormatStrategy < StudentsListFormatStrategy
        def read_from(filename)
            YAML.load_file(filename)
        end
        
        def write_to(filename, students)
            File.open(filename, 'w') do |file|
                file.write(students.to_yaml)
            end
        end
    end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
shnaider_code-2.0.4 lib/source/students_list_format_strategy.rb
shnaider_code-2.0.3 lib/source/students_list_format_strategy.rb
shnaider_code-2.0.2 lib/source/students_list_format_strategy.rb