1 // Copyright 2015 The Bazel Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 /// Object that displays a greeting. 16 pub struct Greeter { 17 greeting: String, 18 } 19 20 /// Implementation of Greeter. 21 impl Greeter { 22 /// Constructs a new `Greeter`. 23 /// 24 /// # Examples 25 /// 26 /// ``` 27 /// use hello_lib::greeter::Greeter; 28 /// 29 /// let greeter = Greeter::new("Hello"); 30 /// ``` new(greeting: &str) -> Greeter31 pub fn new(greeting: &str) -> Greeter { 32 Greeter { 33 greeting: greeting.to_string(), 34 } 35 } 36 37 /// Constructs a new `Greeter` with greeting defined in txt file 38 /// 39 /// # Examples 40 /// 41 /// ``` 42 /// use hello_lib::greeter::Greeter; 43 /// 44 /// let greeter = Greeter::from_txt_file()?; 45 /// ``` from_txt_file() -> std::io::Result<Greeter>46 pub fn from_txt_file() -> std::io::Result<Greeter> { 47 Ok(Greeter { 48 greeting: std::fs::read_to_string( 49 runfiles::Runfiles::create()?.rlocation("rules_rust/test/rust/greeting.txt"), 50 )?, 51 }) 52 } 53 54 /// Returns the greeting as a string. 55 /// 56 /// # Examples 57 /// 58 /// ``` 59 /// use hello_lib::greeter::Greeter; 60 /// 61 /// let greeter = Greeter::new("Hello"); 62 /// let greeting = greeter.greeting("World"); 63 /// ``` greeting(&self, thing: &str) -> String64 pub fn greeting(&self, thing: &str) -> String { 65 format!("{} {}", &self.greeting, thing) 66 } 67 68 /// Prints the greeting. 69 /// 70 /// # Examples 71 /// 72 /// ``` 73 /// use hello_lib::greeter::Greeter; 74 /// 75 /// let greeter = Greeter::new("Hello"); 76 /// greeter.greet("World"); 77 /// ``` greet(&self, thing: &str)78 pub fn greet(&self, thing: &str) { 79 println!("{} {}", &self.greeting, thing); 80 } 81 } 82 83 #[cfg(test)] 84 mod test { 85 use super::Greeter; 86 87 #[test] test_greeting()88 fn test_greeting() { 89 let hello = Greeter::new("Hi"); 90 assert_eq!("Hi Rust", hello.greeting("Rust")); 91 } 92 93 #[test] test_greeting_from_txt_file()94 fn test_greeting_from_txt_file() { 95 let welcome = Greeter::from_txt_file().unwrap(); 96 assert_eq!("Welcome Rust", welcome.greeting("Rust")); 97 } 98 } 99