Sha256: b0d5039f8390ae573468d78854fcaef67ede539ed4d70d5b489f046eed9e62c4

Contents?: true

Size: 1.53 KB

Versions: 3

Compression:

Stored size: 1.53 KB

Contents

require 'json'
require 'yaml'

module RubbishCode
    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
Web_rubbish_code-1.0.2 lib/source/students_list_format_strategy.rb
Web_rubbish_code-1.0.1 lib/source/students_list_format_strategy.rb
Web_rubbish_code-1.0.0 lib/source/students_list_format_strategy.rb